我有一个表单,但Django没有创建像
这样的隐藏输入<input type="hidden" name="csrfmiddlewaretoken" value="80NGejzAPl2aCbEEuyLqIT3ppMTJLilY">
如果尝试发送表单我有403错误,CSRF令牌丢失或不正确。
这是我的代码:
html
<form class="get-info" action="{% url 'callback:send_callback' %}" method="post">{% csrf_token %} ... </form>
中间件
'django.middleware.csrf.CsrfViewMiddleware',
views.py
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect, request
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.template.context_processors import csrf
from django.contrib import messages
def callback(request):
phone = request.POST.get('phone', None)
lastpath = request.POST.get('lastpath', None)
if validatePhone(phone):
if sendMail(phone):
messages.success(request, 'Мы скоро перезвоним Вам')
return HttpResponseRedirect(lastpath)
else:
messages.error(request, 'Ошибка в отправке запроса. Попробуйте позже.')
return HttpResponseRedirect(lastpath)
else:
messages.error(request, "Неверный формат номера телефона. Телефон нужно вводить в формате +99999999999")
args = {}
zzz = lastpath.render(RequestContext(request, args))
return HttpResponse(zzz)
回调网址 -
urlpatterns = [
url(r'^callback/', views.callback, name='send_callback'),
]
主页上的表格渲染:
<form class="get-info" action="/callback/callback/" method="post">
<input type="hidden" name="_subject" value="karpaty-perezvonite-mne">
<input id="callback" name="phone" type="tel" class="form-control" placeholder="+ 380 ___-__-__">
<input type="text" class="form-control" placeholder="" name="lastpath" value="/" style="display: none">
<button type="submit" class="btn btn-default" value="Send">Отправить</button>
</form>
我正在尝试将表单提交到主页面 - “/”现在出现了这样的错误
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.
This is usually caused by not using RequestContext.
我该如何解决?