问题
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' }
回答1:
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.
回答2:
Why only get_context_data
?
Just set up your get
handler to do a redirect if necessary.
def get(self, request, lang):
if lang == 'fr':
return http.HttpResponseRedirect('../en')
return super(MyTemplateView, self).get(request, lang)
来源:https://stackoverflow.com/questions/7884766/can-i-redirect-to-another-url-in-a-django-templateview