Home Django redirect from inside a view
Reply: 1

Django redirect from inside a view

user2239318
1#
user2239318 Published in 2017-12-06 09:42:14Z

I'm using django 1.11.8.

I need to perform some check on the requested view and inside it redirect the user to another Http page, but this code fail, as the redirect is ignored.

What am I missing?

class ThisCreateView(CreateView):

    def get_form_kwargs(self):
         if self.kwargs['x'] == 1:
              return redirect(reverse('this_app:this_list'))
         return kwargs
Alasdair
2#
Alasdair Reply to 2017-12-06 10:17:04Z

You can't return a redirect from the get_form_kwargs method. Its job is to return a dictionary of kwargs for the form.

You could move this check to the dispatch method.

def dispatch(self, request, *args, **kwargs):
     if kwargs['x'] == 1:
          # note you don't need to call reverse when you use redirect
          return redirect('this_app:this_list')
     return super(ThisCreateView, self).dispatch(*args, **kwargs)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.38011 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO