Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class based View: redirect if logged in, else render template

How can I achieve this in the most generic way? I thought of overriding get(), but I'd have to override too many methods. Also tried with as_view() but I can't access the request from there.

I also tried adding a <meta http-equiv="refresh" content="0;url" /> in the template, but I throught that was not the best approach.

like image 214
Alxe Avatar asked May 28 '14 21:05

Alxe


1 Answers

I doubt you want to override as_view unless you are doing something exceptionally odd. It returns a function that is used as the view. The function it returns does little more than call dispatch.

You can override the specific method you want. eg get, alternatively, if you want to override all methods (get, post, etc), you should override dispatch.

from django.shortcuts import redirect
from django.views.generic import TemplateView


class MyView(TemplateView):
    template_name = 'my_app/my_template.html'

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('my-other-view')
        return super(MyView, self).dispatch(request, *args, **kwargs)

CCBV.co.uk is a good reference for learning django's class based views. Disclaimer: I built it.

like image 110
meshy Avatar answered Oct 02 '22 10:10

meshy