0

我想添加一个表单来使用 Django 在我的网站上的多个页面上记录用户。我不想多次复制表单,而是想使用“包含”语句来导入同一个表单。我的代码现在做两件事不正确:它没有显示输入用户名或密码的字段,并且提交表单会产生 CSRF 403(禁止)错误。

示例 html:

        <!-- Login -->
<div id="login">
    <form action="/login/" method="post">
    {% csrf_token %}
    {% include "registration/login_snippet.html" %}
            <p>
            <input type="submit" value="login"/></p>
            </form>
</div> 

login_snippet.html:

{% csrf_token %}
<label for="id_username">
    Username:
</label>
{% if form.username.errors %} 
<span class="error">
{{ form.username.errors|join:", " }}
</span>
{% endif %}
{{ form.username }}
<label for="id_password">
     Password:
</label>
{% if form.password.errors %} 
<span class="error">
    {{ form.password.errors|join:", " }}
</span>
{% endif %}
{{ form.password }}

这是正在显示的内容: 登录表单

任何帮助将不胜感激!

4

2 回答 2

1

Try Adding the following to your code. I am not 100% sure, but I think it should work. Obviously, this disables the csrf protection. However, it should allow you to continue to run your website. While csrf is important, I am not sure that it is mandatory on every single view.

from django.views.decorators.csrf import csrf_exempt
    #Make this a function in your classview

        @csrf_exempt
        def dispatch(self, *args, **kwargs):
            return super(YOUR_VIEW_NAME_HERE, self).dispatch(*args, **kwargs)
于 2013-06-14T17:45:05.520 回答
0

For problem 1 (no field for username and password):

Are you sure the form object is in the context? It seems like there is no {{ form }} that the template has access to, so it can't render {{ form.username }}

For Problem 2 (csrf):

You are including the {% csrf_token %} twice. Once in sample.html and once in login_snippet.html. Removing one of them might solve the issue.

Finally,

Also, is there any reason why the entire login form is not in one snippet? Why separate the 'form' element from the fields?

于 2013-06-14T17:47:00.740 回答