如何将额外的URL值传递给Django generic DeleteView?

2024-04-25 20:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有型号.py地址:

class Parent(models.Model):
    name = models.CharField(max_length=20)

class child(models.Model):
    name = models.CharField(max_length=20)
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)

现在在父对象的详细视图中,我列出了属于父对象的子对象。你知道吗

那个网址.py因为这看起来像

path('parents/<int:pk>/, views.ParentDetailView.as_view(), name='parent-detail')

我会在我的视图中使用django DetailView视图.py像这样

class ParentDetailView(DetailView):
    model = Parent

现在在这个细节视图中,我列出了父对象的子对象,类似于parent_详细信息.html在我的模板中

{{parent}}
{% for child in parent.child_set.all %}
    {{ child.name }}
{% endfor %}

但是我希望能够从这个页面的数据库中删除这个子项,所以我添加了如下内容

{{parent}}
{% for child in parent.child_set.all %}
    {{ child.name }}
    <a href="{% url 'myapp:parent-delete-child" parent.pk child.pk %}">Delete child</a>
{% endfor %}

我被困在这里了! 我很想在我的房间里有这样的东西网址.py你知道吗

path('parents/<int:pk>/', views.ParentDetailView.as_view(), name='parent-detail'),
path('parents/<int:pk>/delete_child/<int:child_pk>/', views.ParentDeleteChildView.as_view(), name='parent-delete-child')

但我不知道如何将pk和child_pk发送到通用的django DeleteView?!?!?!你知道吗

class ParentDeleteChildView(DeleteView):
    model = Child
    success_url = reverse_lazy('myapp:parent-detail' kwargs={'pk':pk})

删除后,我想回到父详细信息页。但是成功的url需要知道父级的pk。如何告诉泛型视图删除与子pk匹配的子,然后转到与pk匹配的父详细信息页?我最好不要使用通用的DeleteView吗?你知道吗

提前谢谢!你知道吗


Tags: path对象namepy视图childmodelsdelete
1条回答
网友
1楼 · 发布于 2024-04-25 20:25:05

我们可以在django中使用get_success_url来实现它。 默认情况下pk_url_kwarg设置为kwarg pk。但在这种情况下,我们必须删除子对象,即child_pk。因此,我们必须通过重写pk_url_kwargchild_pk来提到它。你知道吗

class ParentDeleteChildView(DeleteView):
    model = Child
    pk_url_kwarg = 'child_pk'

    def get_success_url(self):
        success_url = reverse_lazy('myapp:parent-detail' kwargs={'pk':self.kwargs['pk']})
        return success_url

相关问题 更多 >