问题描述
Forbidden (403) CSRF verification Failed. Request aborted. CSRF token missing or incorrect.
setting.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]
view.py
def contact_us(request):
if request.method == "POST":
con_name = request.POST['con_name']
con_email = request.POST['con_email']
con_company = request.POST['con_company']
inquiry = request.POST['inquiry']
con_message = request.POST['con_message']
#context = RequestContext(request)
#context_dict={'con_name':con_name}
#context_dict.update(csrf(request))
return render(request,'contact_us.html',{'con_name':con_name})
else:
return render(request,{})
contact_us.html
<form id="contact-form" action="{% url 'contact_us' %}" method="post">
{% csrf_token %}
<div class="contact-form">
<div class="contact-input">
<div class="contact-inner">
<input name="con_name" type="text" placeholder="Name *">
</div>
<div class="contact-inner">
<input name="con_email" type="email" placeholder="Email *">
</div>
</div>
<div class="contact-inner">
<input name="con_company" type="text" placeholder="Company">
</div>
<div class="contact-select">
<div class="form-item contact-inner">
<span class="inquiry">
<select name="inquiry" class="select-item">
<option value="Your inquiry for">Your inquiry for</option>
<option value="General information Request">General information Request</option>
<option value="Partner Relations">Public Relations</option>
<option value="Digital Marketing">Digital Marketing</option>
<option value="Influencer Marketing">Influencer Marketing</option>
<option value="Brand Creation">Brand Creation</option>
<option value="Careers">Careers</option>
<option value="Brand Creation">Web Development</option>
<option value="Others">Others</option>
</select>
</span>
</div>
</div>
<div class="contact-inner contact-message">
<textarea name="con_message" placeholder="Please describe what you need."></textarea>
</div>
<div class="submit-btn mt-20">
<button class="ht-btn ht-btn-md" type="submit">Send message</button>
<p class="form-messege"></p>
</div>
</div>
</form>
我是Django和大多数Web开发的新手,但我在这里找不到问题。我想念什么?我该如何解决这个问题?
解决方法
您需要在csrf_token的render_to_response中传递RequestContext
为此:(views.py)
from django.template import RequestContext
...
return render_to_response('fileupload/upload.html',{'form':
c ['UploadFileForm']},RequestContext(request))
这会将csrf的令牌传递到模板。
也请访问此Link,这会有所帮助。
,我也遇到了同样的问题。当我在每个输入标签不在一起或被任何其他标签分隔时,在每个输入标签前加上“ {%csrf_token%}”,就可以解决该问题。