Django-ModelForm-UpdateView-pk
我想实现UpdateView,以便更新模型中选定的对象 目前我有: views.pyDjango-ModelForm-UpdateView-pk,django,primary-key,Django,Primary Key,我想实现UpdateView,以便更新模型中选定的对象 目前我有: views.py def fd_detail(request, fdslug): fddetail = Fd.objects.get(slug=fdslug) cffilter = CashFlowFilter(request.GET, queryset=CashFlow.objects.filter(feeder__slug=fdslug)) return render(request, 'fd/fd_
def fd_detail(request, fdslug):
fddetail = Fd.objects.get(slug=fdslug)
cffilter = CashFlowFilter(request.GET, queryset=CashFlow.objects.filter(feeder__slug=fdslug))
return render(request, 'fd/fd_detail.html',
{'fddetail': fddetail,
'cffilter': cffilter,
})
class CashFlowUpdate(UpdateView):
model = CashFlow
fields = ['amount', 'description']
url.py
path('<slug:fdslug>/updatecashflow/', views.CashFlowUpdate.as_view(),name = "update_cashflow"),
path('<slug:fdslug>/', views.fd_detail, name="fd_detail")
path('/updatecashflow/',views.CashFlowUpdate.as_view(),name=“update_cashflow”),
路径(“/”,views.fd_detail,name=“fd_detail”)
更新\u cashflow.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>
{%csrf_令牌%}
{{form.as_p}}
我得到以下错误:“必须使用URLconf中的对象pk或slug调用Generic detail view CashFlowUpdate。”,这意味着我需要传递要更新的对象的主键。。。最好的方法是什么?当前所有“我的对象”都通过表格显示(请参见下文)?我可以添加一个带有url链接“Edit”的列,但是如何将pk放入其中呢
<table class="table table-bordered">
<thead>
<tr>
<th>Amount</th>
<th>Description</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
{% for cashflow in cffilter.qs %}
<tr>
<td> {{cashflow.amount}} </td>
<td> {{cashflow.description}} </td>
<td> ?????? </td>
</tr>
{% empty %}
<tr>
<td colspan="5"> No cashflow matches your search criteria</td>
</tr>
{% endfor %}
</tbody>
</table>
数量
描述
编辑
{cffilter.qs%中的现金流百分比}
{{现金流.金额}
{{cashflow.description}
??????
{%empty%}
没有与您的搜索条件匹配的现金流
{%endfor%}
非常感谢就像错误说的那样:
必须使用URLconf中的对象pk或slug调用通用详细视图CashFlowUpdate
更新视图通常需要某种URL参数来确定要更新的对象。它隐式地旨在检查两个字段:slug和主键。但是在您的URL.py
中,您使用了fdslug
作为URL参数
这可以通过自己指定一个解决方案来轻松解决,如:
class CashFlowUpdate(UpdateView):
model = CashFlow
fields = ['amount', 'description']
slug_url_kwarg = 'fdslug'
F
这里有模型吗?在Django中,有一个基本上代表“字段”的F
,因此为了避免“名称冲突”,最好给模型一个更具描述性的名称。是的,这是一个模型。好的观点&我改变了,但仍然是相同的错误信息。嗨,威廉。好的,谢谢,让我试试。但使用主键的解决方案是什么?谢谢again@TMD:w所有pk\u url\u kwarg
默认设置为pk
。因此,您可以在URL中添加pk
(或者将pk\u URL\u kwarg
的值更改为主键URL参数的名称)而不是slug。
<td><a href="{% url 'update_cashflow' fdslug=cashflow.slug %}">edit</a></td>