Search code examples
pythondjangowebdjango-templatesdjango-authentication

How to import request.user into TemplateVew in djnago


I need to know how I can check if a user is authenticated user the TemplateView methods of rendering pages.

i have added this into my context processors:

    TEMPLATE_CONTEXT_PROCESSORS = [
    'django.contrib.auth.context_processors.auth',
]

my views.py currently looks like :

    from django.shortcuts import render
from CreateVuln.forms import *
from django.views.generic import TemplateView
from django.template import RequestContext

from pages.decorators import *

vulnform = vulnform


class Dashboard(TemplateView):
    template_name = 'vuln_pages/Create_Vuln.html'

    def get(self, request):
        Outform = {
                     'vulnform': vulnform,

                     }
        return render(request, self.template_name, Outform)

    def post(self, request):
            forminput = vulnform(request.POST or None)


            if forminput.is_valid():
                forminput.save()
                forminput = vulnform()



                inoutform = {
                             'vulnform': forminput,

                             }
                return render(request, self.template_name, inoutform, )

            else:

                inoutform = {
                             'vulnform': vulnform,

                             }

                return render(request, self.template_name,inoutform )

# Create your views here.

class ViewVulns(TemplateView):

    template_name = 'vuln_pages/Create_Vuln.html'

    def get(self, request):

        return render(request, self.template_name)

I want to make it so the page cannot be viewed with either a GET request and cannot be updated with a POST request. i've tried using RequestContext. but the documentation seems convoluted and i cannot seem to understand how to use it.


Solution

  • Use LoginRequiredMixin mixin

    If a view is using this mixin, all requests by non-authenticated users will be redirected to the login page or shown an HTTP 403 Forbidden error, depending on the raise_exception parameter.

    from django.contrib.auth.mixins import LoginRequiredMixin
    
    
    class Dashboard(LoginRequiredMixin, TemplateView):
        # your code