Doug Smith
Doug Smith

Reputation: 580

django DeleteView - how to pass a parameter to use for success_url?

I am using a DeleteView where the I want to the success_url to be the view that called the DeleteView. This success_url requires two parameters to be passed to it.

model

class Part(models.Model):
    name = models.CharField(max_length=20)
    worker = models.ForeignKey(Worker, on_delete=CASCADE)
    company = models.ForeignKey(Company, on_delete=CASCADE)

urls.py

path('listparts/<uuid:company_pk>/<uuid:worker_pk>/', views.listparts, name='listparts'),
path('deletepart/<uuid:part_pk>/', views.PartDeleteView.as_view(), name='deletepart'),

view

def listparts(request, company_pk, worker_pk):
    ...
    ...

class PartDeleteView(DeleteView):
    model = Part
    success_url = reverse_lazy('listparts' company_pk worker_pk)

listparts template

<a href="{% url 'deletepart' part_pk %}">Delete this part</a>

confirm_delete template

<div class="row">
    <div class="col-md-3">
      <form class="form-group">
        {% csrf_token %}{{ form|crispy }}
          <div class="form-group">
            <p>Are you sure you want to delete "{{ object }}"?</p>
          <input type="submit" class="btn btn-primary mt-2 mb-2" value="Update">
        </div>
      </form>
    </div>

But I don't know how to deal with that in the DeleteView. I'm sure it has to do with dealing with kwargs but I'm still learning on how kwargs work in something like def get_success_url(self)

Edit I have included a model for Part and the template for the confirm_delete. From Willem Van Onsem's comment, I have modified the PartDeleteView to:

class PartDeleteView(DeleteView):
    model = Part

    def get_success_url(self, *args, **kwargs):
        return reverse_lazy('listparts', args={'company_pk':self.company.pk, 'worker_pk':self.worker.pk})

With this code, after I click the link to delete a part, I'm taken to the confirm_delete template. Clicking the Update button doesn't do anything. The page is taken to the success_url, and the part is not deleted.

Upvotes: 2

Views: 1171

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477180

I think it makes more sense here to override the get_success_url, and thus implement this as:

from django.urls import reverse

class PartDeleteView(DeleteView):
    model = Part

    def get_success_url(self):
        return reverse(
            'listparts',
            kwargs={
                'company_pk': self.object.company_id
                'worker_pk': self.object.worker_id
            }
        )

Here self.object is the object that has been removed, and we thus access the company_id and worker_id of that object as kwargs=… for the URL we generate.

Upvotes: 4

Related Questions