简体   繁体   中英

Django redirectView returns None

I'm trying to use redirect view in django, but I keep getting this error:

The view gp_accountant.gp_taxes.views.TaxRateDeleteView didn't return an HttpResponse object. It returned None instead.

I've based my code on this question .

Anyone knows where the problem lies?

This is my url file (path: get-paid/gp_accountant/gp_taxes/urls.py ):

app_name = 'gp_taxes'
urlpatterns = [
    url(r'^$', TaxesListView.as_view(), name='list'),
    url(
        r'^delete_rate/(?P<pk>\d+)/$',
        TaxRateDeleteView.as_view(pattern_name='accountant:gp_taxes:update'),
        name='delete_rate'
    ),
]

The TaxRateDeleteView:

class TaxRateDeleteView(RedirectView):
    def dispatch(self, request, *args, **kwargs):
        TaxRate.objects.get(id=int(kwargs['pk'])).delete()

@FazilZaid almost correct, you need to return last line of his answer. Problem is that your dispatch doesn't return anything in general it should return HttpResponseRedirect so to make it work with super call you need to provide success_url to your view

class TaxRateDeleteView(RedirectView):
    success_url = # <- your url here

    def dispatch(self, request, *args, **kwargs):
        TaxRate.objects.get(id=int(kwargs['pk'])).delete()
        return super(TaxRateDeleteView,self).dispatch(request, *args, **kwargs)

Also as per this comment by @Alasdair

Using a redirect view for deleting objects is a bad idea. You should not be deleting objects with get requests like this.

You should use https://docs.djangoproject.com/en/1.11/ref/class-based-views/generic-editing/#django.views.generic.edit.DeleteView which is right way to delete object, instead of RedirectView

Edit your view,

class TaxRateDeleteView(RedirectView):
    def dispatch(self, request, *args, **kwargs):
        TaxRate.objects.get(id=int(kwargs['pk'])).delete()
        return super(TaxRateDeleteView,self).dispatch(request, *args, **kwargs)

Call super on dispatch method of your view.

You shouldn't be overriding the dispatch method.

Try something like this instead:

class TaxRateDeleteView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        TaxRate.objects.get(id=int(kwargs['pk'])).delete()   
        return reverse('delete_rate')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM