How to return a TemplateView.as_view() if user is authenticated?

Viewed 36
# urls.py
from django.contrib import admin
from django.urls import path, include
from home import views
from django.views.generic import TemplateView


urlpatterns = [ 
    path('',views.index, name="home"),
    path('', TemplateView.as_view(template_name='index.html')),
    path('login',views.loginUser, name="login"),
    path('logout',views.logoutUser, name="logout"),
]

Above is my urls.py file.

# views.py
from django.views.generic import TemplateView

def index(request):
    print(request.user)
    if request.user.is_anonymous:
        return redirect("/login") 
    return render(request, TemplateView.as_view(template_name="about.html"))
.
.
.

Above is a part of my views.py

I'm trying to return/render my "index.html" file as a TemplateView.as_view() (as I am using React on the frontend) ONLY if the user is authenticated. I have handled the authentication part, I need help figuring out how to write code to return/render index.html file as a TemplateView.as_view().

Thanks.

Edit:

Even though return render(request, "index.html") works, my React frontend becomes static and I can't use my CRUD functions. That's why I need to use TemplateView but I don't know how to in my situation.

3 Answers

If you want to render the template using TemplateView you have to use a class-based view. You are using a function-based view, so can render the template as:

def index(request):
    if request.user.is_anonymous:
       return redirect("/login") 
    return render(request, "about.html")

For Class based view You can check official documentation of Django here

Here is an example how you can do it. I would advise you to use CBV and use LoginRequiredMixin.

from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin


class Something(LoginRequiredMixin, TemplateView)
    login_url = '/login/'
    redirect_field_name = 'login'
    template_name = "about.html"

Bookmark Classy Class-based Views

You want to check that the user is authenticated before showing hom the page. There are two ways. One is to subclass an appropriate method in the view. get, probably.

def get (self, request, *args, **kwargs):
    if request.user.is_anonymous:
        return redirect("/login") 
    return super().get( request, *args, **kwargs)

The other is to employ one of the mixins provided by the Django framework, in this case LoginRequiredMixin as per Ramil's answer

This second is best if LoginRequiredMixin does what you want. Subclassing get (or dispatch or setup) is appropriate if the supplied mixin doesn't do what you want, so you inject your own code.

Related