Django POST常见的错误:CSRF verification failed. Request aborted.

时间:2021-02-07 19:30:33

直接用代码说明吧。

在Post模板页面加入{%csrf_token%}

<html>
<body>
{{result}}
	<form  action="{%url 'login'%}" method="post">			  	          	
 	 {% csrf_token %}  
 	name:<input type="text" id="username" name="username" value="super"/>			            	   	            	
   	password:<input type="password"  id="password" name="password"/>
	
	 <input type="submit" value="login" />
</form>
</body>
</html>

把和POST页面相关的所有view的context强制换成RequestContext

 return render_to_response('wind/index.html',context,context_instance=RequestContext(request) )
记得加入 

from django.template import RequestContext   
完整例子:

from django.shortcuts import render
from django.shortcuts import render,render_to_response
from django.template import RequestContext   
from django.contrib.auth.models import User
from django.contrib import auth
from wind.models import UserProfile
from django.core.context_processors import csrf  
# Create your views here.
'''
index
'''
def  index(request):
    context={"js":"hello baby"}
    return render_to_response('wind/index.html',context,context_instance=RequestContext(request) )
'''
login 
'''
def  login(request):
    username = request.POST['username']
    password = request.POST['password']
    user=auth.authenticate(username=username,password=password)
    if user is not None:
        if user.is_active:
        	auth.login(request,user)
        	context={'result':'login success!'}
    else:
        context={'result':'login failed!'}
    return render_to_response('wind/index.html',context,context_instance=RequestContext(request) )