这是我的注册视图,我使用 ajax 发布。我是按照官方文档的。如果 csrftoken cookie 存在,它可以正常工作。
但是,返回 json 数据的视图没有设置 csrftoken。如何处理?
def signup(request):
if request.method == "POST":
postdata = request.POST.copy()
form = UserCreationForm(postdata)
if form.is_valid():
form.save()
user = postdata.get('username', '')
password = postdata.get('password1', '')
from django.contrib.auth import login, authenticate
new_user = authenticate(username=user, password=password)
if new_user and new_user.is_active:
login(request, new_user)
data = json.dumps({'success': 'true'})
return HttpResponse(data, mimetype='application/json')
else:
data = json.dumps({'username': '该用户处于非正常状态'})
return HttpResponse(data, mimetype='application/json')
else:
error_list = {}
for ek in form.errors:
error_list[ek] = form.errors[ek][0]
data = json.dumps(error_list)
return HttpResponse(data, mimetype='application/json')
else:
return HttpResponseRedirect("/")