我有一个登录表单,希望在所有视图中都能使用,因此创建了一个上下文处理器以将该表单添加到所有加载的上下文中。
问题是,表单模板上的
以下是
表单模板:
这个表单的HTML输出为:
问题是,表单模板上的
{% csrf_token %}
不会呈现CSRF令牌值的隐藏输入标签。以下是
settings.py
中的上下文处理器顺序:TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
'django.core.context_processors.csrf',
'absolute.context_processors.absolute',
'myproject.app.context_processors.base',
)
然后处理器本身位于app/context_processors.py
:
from django.contrib.auth.forms import AuthenticationForm
def base(request):
context = dict()
if not request.user.is_authenticated():
context['login_form'] = AuthenticationForm()
return context
表单模板:
{% load i18n %}
<form method="post" action="{% url "django.contrib.auth.views.login" %}">
{% csrf_token %}
<input type="hidden" name="next" value="{% if request.GET.next %}{{ request.GET.next }}{% else %}{{ request.get_full_path }}{% endif %}" />
{{ login_form.as_p }}
<input type="submit" class="button success expand" value="{% trans 'Login' %}" />
</form>
这个表单的HTML输出为:
<form action="/accounts/login/" method="post">
<input type="hidden" value="/" name="next">
<p><label for="id_username">Usuário:</label> <input type="text" name="username" maxlength="254" id="id_username"></p>
<p><label for="id_password">Senha:</label> <input type="password" name="password" id="id_password"></p>
<input type="submit" value="Login" class="button success expand">
</form>
当我提交时出现的错误:
CSRF verification failed. Request aborted.
然而,由于我只使用基于类的视图,如果我添加一个csrf_protect
装饰器,表单将会正常工作,但是这样一来我必须在所有的视图中声明dispatch
方法:
from django.views.decorators.csrf import csrf_protect
class HomeView(TemplateView):
template_name = 'home.html'
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
问题状态
我放弃了在所有视图中放置AuthenticationForm,而是创建了一个登录表单页面。无论如何,如果有人能帮助我找到解决这个问题的方法,那将是非常棒的。
'myproject.app.context_processors.base'
中删除myproject.
。 - Steinar Limamyproject
将会导致导入错误:No module named app.context_processors
。 - vmassuchetto