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

Time:01-22

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.

CodePudding user response:

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()
  • Related