django - 在 base.html 中包含 Django 登录表单

标签 django authentication django-forms

我是 Django 的新手,我想在基本 html 中包含我的登录表单。

我有以下内容:

“注册/登录.html”

{% if form.has_errors %}
    <p>Your username and password didn't match.
        Please try again.</p>
{% endif %}
<form method="post" action=".">
    {% csrf_token %}
    <p><label>Username:</label>
        {{ form.username }}</p>
    <p><label>Password:</label>
        {{ form.password }}</p>
    <input type="submit" value="login" />
    <input type="hidden" name="next" value="/" />
</form>

网址.py

url(r'^login/$', 'django.contrib.auth.views.login'),

我在 base.html 中包含以下内容:

{% include "registration/login.html" %}

它呈现除用户名和密码文本框以外的所有内容。我想我错过了什么。

最佳答案

好吧,我认为问题在于您期待“魔法”。

Django 的 View 是模板非常愚蠢。他们只有以两种方式之一传递的可用变量:

  1. 通过 context_processor(参见 Aidan 的回答)
  2. 调用render(或render_to_response)时传入

当您访问 /login 时表单呈现的原因,但在其他情况下,是因为您使用的 Django View django.contrib.auth.views.login,为您将 Django AuthenticationForm 传递到您的模板中。

在此处查看来源: https://github.com/django/django/blob/master/django/contrib/auth/views.py

没有其他 View “神奇地”获得该变量集。

所以你必须:

  1. 在整个应用的每个 View 中自行设置
  2. 使用上下文处理器。

这是一个简单的 context_processors.py,它使用 Django 的东西(基于 Aidan 的):

def include_login_form(request):
    from django.contrib.auth.forms import AuthenticationForm
    form = AuthenticationForm()
    return {'login_form': form}

然后,按照 Aidan 指出的那样做:

TEMPLATE_CONTEXT_PROCESSORS = (
    #....
    'yourapp.context_processors.include_login_form'
)

现在的问题是,当您只包含模板时,登录表单位于名为“login_form”的变量中,但是当 django 的内置 View 使用您的模板时,它位于名为“form”的变量中。

因此,如果没有一个好的“干净”解决方案,那将是一场考验,尽管我相信有人可以解决这个问题。

也许检查在你的 context_processor 中传入的上下文,如果一个名为“form”的变量已经存在,看看它是否是 AuthenticationForm 的一个实例,如果是,就使用它。

关于django - 在 base.html 中包含 Django 登录表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086292/

相关文章:

python - 在 Django 中提交表单后停止页面重定向

django - 合并 angular 和 Django 的 url

Python 在文件结束之前退出 CSV 文件

Python urllib2、基本 HTTP 身份验证和 tr.im

authentication - Azure移动应用程序刷新服务器上的 token

django - 如何在 Django 表单中使用 TimeInput 小部件?

python - Django 在模板中获取 ContentType

python - 引发 RuntimeError ('You need to use the eventlet server. '

asp.net - Web api 和 Angularjs 身份验证失败

python - 切换祖先顺序会破坏初始化吗?