Home > Software engineering >  How to return a TemplateView.as_view() if user is authenticated?
How to return a TemplateView.as_view() if user is authenticated?

Time:09-08

# 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.

CodePudding user response:

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"

CodePudding user response:

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

  • Related