50
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().dispatch(request, *args, **kwargs)
Keep your business logic in your dispatch
and you should be golden.
15
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)
- [Django]-Is it possible to pass query parameters via Django's {% url %} template tag?
- [Django]-Django: remove a filter condition from a queryset
- [Django]-Count() vs len() on a Django QuerySet
- [Django]-Django β comparing old and new field value before saving
- [Django]-How do I make an auto increment integer field in Django?
- [Django]-How can I serialize a queryset from an unrelated model as a nested serializer?
1
This worked for me using an UpdateView
class in Django 3.1:
def get(self, request, *args, **kwargs):
if 1 == 1:
return HttpResponseRedirect(reverse_lazy("view_name_here"))
else:
return super().get(request, *args, **kwargs)
To determine this, I analyzed its base class (Cmd+Click in PyCharm), where I found the base method:
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super().get(request, *args, **kwargs)
You can find this and other methods in the Django source code: django/views/generic/edit.py
- [Django]-Django comparing model instances for equality
- [Django]-Django "Remember Me" with built-in login view and authentication form
- [Django]-Django: relation "django_site" does not exist
Source:stackexchange.com