Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I redirect to another url in a django TemplateView?

I have a url mapping that looks like this:

url(r'^(?P<lang>[a-z][a-z])/$', MyTemplateView.as_view()), 

There are only a few values that I accept for the lang capture group, that is: (1) ro and (2) en. If the user types http://server/app/fr/, I want to redirect it to the default http://server/app/en/.

How can I do this since MyTemplateView only has a method that is expected to return a dictionary?

def get_context_data(self, **kwargs):     return { 'foo': 'blah' } 
like image 403
canadadry Avatar asked Oct 25 '11 04:10

canadadry


1 Answers

I know this question is old, but I've just done this myself. A reason you may think you want to do it in get_context_data is due to business logic, but you should place it in dispatch.

def dispatch(self, request, *args, **kwargs):     if not request.user.is_authenticated():         return redirect('home')      return super(MyTemplateView, self).dispatch(request, *args, **kwargs) 

Keep your business logic in your dispatch and you should be golden.

like image 73
johndavidback Avatar answered Oct 18 '22 17:10

johndavidback