需要帮助才能在Django项目的所有应用程序中使用身份验证吗

2024-05-29 10:56:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始使用Django,对于服务器端代码我只是个新手。我所有的网页编码经验都是在前端,仅限于CSS、HTML和基本javascript。但我认为是时候提高一个档次,了解更多的事情的后端,并决定从这里开始。我成功地通过了Django的入门申请指南。我并不是想在应用程序中添加一个扩展名,并给它“添油加醋”。你知道吗

我为注册/用户管理安装了allauth。我能够设置它,并成功地注册,登录,注销与默认模板。你知道吗

但是,当我加载同一个项目中的polls应用程序时,它似乎不起作用。。。你知道吗

代码输入索引.html(在templates/polls/下找到)在无法工作的polls应用程序下。你知道吗

{% if user.is_authenticated %}
    <b>ALL GOOD</b>
{% else %}
    <b>Go sign-in first.</b>
{% endif %}

密码输入标志-向上.html(在templates/account/下找到)在有效的帐户下。你知道吗

{% if user.is_authenticated %}
    Good work
{% else %}
    Fail
{% endif %}

我是不是少了一份进口报关单?为什么它在一个模板文件夹中工作而在另一个文件夹中不工作?你知道吗

提前谢谢!你知道吗


Tags: django代码文件夹模板应用程序ifishtml
3条回答

如果您使用RequestContext(request)并且在TEMPLATE_CONTEXT_PROCESSORS中有django.contrib.auth.context_processors.auth,那么user变量可以在模板上访问。你知道吗

https://docs.djangoproject.com/en/dev/ref/templates/api/#django-contrib-auth-context-processors-auth

我觉得这在我脑子里更有意义。你知道吗

RequestContext来自from django.template import RequestContext并且当您

render_to_response("mytemplate.html",
    RequestContext(request, {"other_variable": other_value, "more": True}))

template.render(RequestContext(request, {"other_variable": other_value, "more": True}))

简单地说:您可以访问一堆变量,而不必指定它们。你知道吗


编辑:-

我发现你可以用from django.views.generic.simple import direct_to_template代替render_to_response

direct_to_template(request, "mytemplate.html", {"other_variable": other_value, "more": True})

它的作用与我上面给出的render_to_response行相同。你知道吗

如果没有更多的信息,很难说,但我最初的反应是,您可能没有将用户变量传递给视图函数中的模板上下文。你知道吗

即:

def view(request):
    t = loader.get_template('index.html')
    c = Context({"user": request.user})
    return HttpResponse(t.render(c))

试试request.user.is_authenticated。你知道吗

相关问题 更多 >

    热门问题