Reputation: 165
Suppose I have models.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)
Now in the Detail View of a Parent I list out the children that belong to the parent.
The urls.py for this would look like
path('parents/<int:pk>/, views.ParentDetailView.as_view(), name='parent-detail')
And I'd use a django DetailView in my views.py like this
class ParentDetailView(DetailView):
model = Parent
Now in this detail view I list out the children of the parent with something like parent_detail.html in my templates
{{parent}}
{% for child in parent.child_set.all %}
{{ child.name }}
{% endfor %}
But I'd like to be able to delete the child from the database from here on this page, so I'd add something like
{{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 %}
Here's where I'm stuck! I would love to have something like this in my urls.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')
But I have no idea how to send the pk and the child_pk to the generic django DeleteView?!?!?!
class ParentDeleteChildView(DeleteView):
model = Child
success_url = reverse_lazy('myapp:parent-detail' kwargs={'pk':pk})
After deleting I want to go back to the parent detail page. But the success url needs to know the pk of the parent. How do I tell the generic view to delete the child that matches the child_pk and then go to the parent detail page that matches the pk? Am I better off not using the generic DeleteView?
Thanks in advance!
Upvotes: 0
Views: 341
Reputation: 11695
We can achieve it using get_success_url
in django
.
By default pk_url_kwarg
is set to kwarg pk
. But in this case we have to delete child object i.e child_pk
. so, we have to mention it by overriding pk_url_kwarg
to child_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
Upvotes: 2