你好,我想删除模型中的对象,但是我不想在标签中显示id,所以我意识到我可以通过表单中的隐藏标签发送数据,但是我没有设法使它工作
模板
Mutex
网址。检查我不要
<form action="{% url "delete_url" %}" method="post">
{% csrf_token %}
<input type="hidden" name="pk" value={{ model.pk }}>
<button type="submit">Delete</button>
</form>
查看
path("delete_view", views.MyDeleteView.as_view(), name="delete_url")
答案 0 :(得分:1)
首先,您的示例代码存在各种问题,需要解决:
hidden
,而不是hiden
。MyDeleteView
,而不是delete_view
现在,针对您的实际问题:DeleteView
使用SingleObjectMixin
来标识对象(请检查https://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/DeleteView/)。因此,您需要重写get_object
的{{1}}方法,以便使用SingleObjectMixin
数据而不是块来检索对象。可能类似的事情应该起作用(警告没有错误处理):
class MyDeleteView(DeleteView): model=ModelName success_url = reverse_lazy("success_url") def get_object(self, queryset=None): pk = self.request.POST['pk'] return self.get_queryset().filter(pk=pk).get()
有关CBV的简要介绍,我推荐我的CBV指南:https://spapas.github.io/2018/03/19/comprehensive-django-cbv-guide/
答案 1 :(得分:0)
感谢Serafeim,我找到了实现的方法,我必须替换get_object()方法并从原始方法中复制一些代码。我从链接获取代码: https://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/DeleteView/
最终:
class MyDeleteView(DeleteView):
model=ModelName
success_url = reverse_lazy("success_url")
def get_object(self, queryset=None):
pk = self.request.POST['pk']
if queryset is None:
queryset = self.get_queryset()
if pk is not None:
queryset = queryset.filter(pk=pk)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404("No %(verbose_name)s found matching the query" %
{'verbose_name': queryset.model._meta.verbose_name})
return obj