django - 获取 ValuError:字段 'id' 需要一个数字,但得到一个 html
问题描述
我是一个新手,自学 Django 大约 10 天,我正在构建一个 Django (v3.2) 应用程序。应用中的主视图是一个国家列表(视图:CountryListView,模板:country_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)
视图.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')
网址.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'),
country_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,带有两个导航按钮(返回列表),以及编辑表单(这是不起作用的)。
{% 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
的按钮属性包含无效的网址:
<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>