获取值错误:字段'id'期望一个数字,但得到一个 html



我是一个新手,自学Django大约10天了,我正在构建一个Django(v3.2(应用程序。应用程序中的主视图是国家列表(视图:CountryListView,模板:countries_view.html(。当我点击该列表中的一个国家时,会弹出一个详细视图,以查看详细的国家数据(CountryDetailView和country_detail.html(。在CountryDetailView中,有导航按钮:返回CountryListView,或"编辑",将用户带到CountryEditView,在那里可以更改国家参数&已保存。

然而,当我点击"编辑"时,我会得到以下错误:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/manage_countries/countries/country_edit.html/
Django Version:     3.2.4
Exception Type:     ValueError
Exception Value:    Field 'id' expected a number but got 'country_edit.html'

我猜这可能是对从CountryDetailView返回的值(或者更确切地说是预期但未返回的值(做一些事情,但它们是什么?以及如何使CountryDetailView返回对象id?(我在我的模型中使用纯整数id(

views.py

class CountryListView(LoginRequiredMixin, ListView):
model = Countries
context_object_name = 'countries_list'
template_name = 'manage_countries/countries_view.html'
class CountryDetailView(LoginRequiredMixin, DetailView):
model = Countries
template_name = 'manage_countries/country_detail.html'
class CountryEditView(LoginRequiredMixin, UpdateView):
model = Countries
template_name = 'manage_countries/country_edit.html'
success_url = reverse_lazy('manage_countries:countries_view')

urls.py

path('', CountryListView.as_view(),name='countries_view'),
path('countries/<pk>/', CountryDetailView.as_view(), name='country-detail'),
path('<pk>/edit', CountryEditView.as_view(), name='country_edit'),

countries_view.html

{% block content %}
<div class="list-group col-6">
<a href="country_add.html" class="list-group-item list-group-item-action shadow-mt list-group-flush list-group-item-dark text-light">Click here to add country data</a>
{% for country in countries_list %}
<a href="{{ country.get_absolute_url }}" class="list-group-item list-group-item-action shadow-mt list-group-flush list-group-item-light"><small><span class="text-dark">{{ country.name }}</span></small></a>
{% endfor %}
</div>
{% endblock content %}

country_detail.html,带有两个导航按钮(返回列表(,并进一步指向Edit form(这是一个不起作用的按钮(。

{% block content %}
<div class="card col-5 shadow-mt">
<h5 class="card-header bg-light text-center">Country data</h5>
<div class="card-body">
<table class="table">
<thead><tr>
<th scope="col"><small>Name: </small></th>
<th scope="col"><small>{{ object.name }}</small></th>
</tr></thead>
</table>
<button class="btn btn-secondary mt-3" onclick="javascript:history.back();">Back</button>
<button class="btn btn-secondary mt-3" onclick="window.location.href='../country_edit.html';">Edit</button>
</div>
</div>
{% endblock content %}

按钮的onclick属性包含无效的url:

<button>onclick="window.location.href='../country_edit.html';">Edit</button>

使用模板标签url(Django Docs(:

<button class="btn btn-secondary mt-3" onclick="window.location.href='{% url 'country_edit' object.pk %}';">Edit</button>

最新更新