首页 > 解决方案 > Django:在另一个视图中显示登录表单的问题

问题描述

我正在构建一个 Django 应用程序,如果没有用户登录,我会在其中显示一个登录页面。我已经按照设置步骤操作,默认登录页面就像一个魅力,从以下位置访问:accounts/login/。现在我想在我的登录页面视图中显示该登录表单。我尝试添加一个上下文处理器,但它还没有工作。这是所有信息:

我的模板目录中的文件结构是:

在landing.html中,我有这样的东西:

{% block content %}

Welcome message, blah blah

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

More contents, etc

{% endblock content %}

问题: 当我打开登录页面时,显示“登录”按钮,但不显示输入字段!当我检查 DOM 时,表格在那里,但 td 元素是空的(请参阅下面的差异)。我在 Chrome 检查器中看到的另一个区别(不确定它是否重要):在我的landing.html 中,它显示Shadow Content (User Agent)在每个输入元素之后

(工作)默认登录页面上使用的登录表单:

<form method="post" action="/accounts/login/">
    <input type="hidden" name="csrfmiddlewaretoken" value="wxidpSfyGmszybrJC38AC8kA8BTylBwiwVONPotCIqOYbkDF54Gwu1ME3lRLTxGw">
    <table>
      <tbody><tr>
        <td><label for="id_username">Username:</label></td>
        <td><input type="text" name="username" autofocus="" autocapitalize="none" autocomplete="username" maxlength="150" required="" id="id_username"></td>
      </tr>
      <tr>
        <td><label for="id_password">Password:</label></td>
        <td><input type="password" name="password" autocomplete="current-password" required="" id="id_password"></td>
      </tr>
    </tbody></table>
    <input type="submit" value="login">
    <input type="hidden" name="next" value="">
  </form>

通过landing.html进入DOM的登录表单:

<form method="post" action="/accounts/login/">
    <input type="hidden" name="csrfmiddlewaretoken" value="zd8knaLCEclaAtNViVNSg7MgpJX15AgkzBEUNGZGGgHzdCZRLWlO80ekktVeDwqy">
    <table>
      <tbody><tr>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
      </tr>
    </tbody></table>
    <input type="submit" value="login">
    <input type="hidden" name="next" value="">
  </form>

在阅读了 7 年前的这篇文章后,我添加了一个上下文处理器,但它似乎没有任何效果,所以我想知道事情是否发生了一些变化(我使用的是 django 3.2)。

在我的应用程序目录中,我添加了 context-processors.py,其中:

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

我更新了我的 settings.py 以包含它:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': str(os.path.join(BASE_DIR, 'templates')),
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'myapp.context_processors.include_login_form',
            ],
        },
    },
]

有人看到我可能会错过什么吗?提前非常感谢!

标签: djangodjango-viewsdjango-forms

解决方案


推荐阅读