【问题标题】:How to import request.user into TemplateVew in djnago如何在 django 的 TemplateView 中导入 request.user
【发布时间】:2020-04-02 14:32:01
【问题描述】:

我需要知道如何通过 TemplateView 渲染页面的方法检查用户是否是经过身份验证的用户。

我已将此添加到我的上下文处理器中:

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

我的 views.py 目前看起来像:

    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)

我想这样做,这样页面就不能用 GET 请求查看,也不能用 POST 请求更新。 我试过使用 RequestContext。但文档似乎令人费解,我似乎无法理解如何使用它。

【问题讨论】:

    标签: python django web django-templates django-authentication


    【解决方案1】:

    使用LoginRequiredMixinmixin

    如果视图使用此 mixin,则所有未经身份验证的用户的请求都将被重定向到登录页面或显示 HTTP 403 Forbidden 错误,具体取决于 raise_exception 参数。 p>

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

    【讨论】:

      【解决方案2】:

      你可以试试这个:if request.user.is_authenticated:

      【讨论】:

        猜你喜欢
        • 2016-12-27
        • 1970-01-01
        • 2018-05-29
        • 1970-01-01
        • 2011-12-23
        • 2018-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多