Can I redirect to another url in a django TemplateView?
Asked Answered
H

5

32

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' }
Herron answered 25/10, 2011 at 4:36 Comment(0)
H
51

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.

Hoe answered 16/4, 2013 at 13:5 Comment(0)
M
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)
Mattiematting answered 25/10, 2011 at 4:57 Comment(0)
A
2

A note from the future: it's now possible and probably simpler just to use RedirectView.

Alb answered 25/11, 2020 at 19:59 Comment(0)
M
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

Mcdonough answered 10/1, 2021 at 4:25 Comment(0)
P
1

You're looking for this syntax.

call the URL from your template like:

{% url 'wiki' %}

inside your urls.py:

urlpatterns = [
path('wiki/', RedirectView.as_view(url='https://wikipedia.com'), name='wiki'),
]

Notice the parameter changed from template_name to url inside as_view() function.

Penetrating answered 30/4, 2024 at 23:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.