How can I skip pk in url while redirecting to another url with generic RedirectView in Django?

I am trying to delete a record after displaying it with DetailView and redirecting to the list page again.

view.py

...

class DailyRecordDeleteConformationView(RequiredBasicDetailsAndContextMixin, DetailView):
    model = DailyRecord
    obj_not_found_redirect = reverse_lazy('business:add_daily_records')
    template_name = 'business/daily_records_detail.html'
    context_object_name = 'record'

    def get_object(self):
        detail = self.model.custom_obj.get_single(self)
        return detail


class DailyRecordDeleteView(RequiredBasicDetailsMixin, RedirectView):
    pattern_name = 'business:daily_records'

    def get_redirect_url(self, *args, **kwargs):
        # Delete the record
        return super().get_redirect_url(*args, **kwargs)

...

urls.py

...
    path('daily-records/', DailyRecordView.as_view(), name='daily_records'),
    path('daily-records/<int:pk>/', DailyRecordDeleteConformationView.as_view(), name='daily_record_detail'),
    path('daily-records/<int:pk>/delete/', DailyRecordDeleteView.as_view(), name='daily_record_delete'),

...

Here I am getting this below error when click on the delete button on detail view

NoReverseMatch at /business/daily-records/7/delete/

Reverse for 'daily_records' with keyword arguments '{'pk': 7}' not found. 1 pattern(s) tried: ['business/daily\\-records/\\Z']

I am new to class based views, and still not able to figure out how to redirect to url that does not have the pk parameter.

I tryed to find any variable for RedirectView or something that can skip the pk of current url while redirecting to another url.

Thanks.

When you invoke get_redirect_url with **kwargs, your pk is in kwargs and in RedirectView, Django tries to get your url with that kwargs.

So if you don't want to pass the pk, just don't pass kawrgs:

def get_redirect_url(self, *args, **kwargs):
    return super().get_redirect_url()

You can specify url instead of pattern_name, so:

from django.urls import reverse_lazy


class DailyRecordDeleteView(RequiredBasicDetailsMixin, RedirectView):
    urls = reverse_lazy('business:daily_records')

    # no get_redirect_url

Your get_redirect_url is also not supposed to delete records: the HTTP protocol specifies that GET and OPTION should be "safe" methods, that means they should not have side-effects.

You thus should delete records with a POST/DELETE request. You can work with a small FormView that will tackle this in case the (empty) form is valid, so by overriding the form_valid method.

Back to Top