我不明白这一个......
令牌在模板中,'django.middleware.csrf.CsrfViewMiddleware'在MIDDLEWARE_CLASSES中定义
views.py:
from django.shortcuts import render_to_response
from ezmapping.models import *
from django.forms.models import modelformset_factory
def setMapOptions(request):
ezMapFormSet = modelformset_factory(ezMap, fields=('map_name', 'zoom_level', 'center_lat', 'center_long', 'map_width', 'map_height'))
if request.method == 'POST':
formset = ezMapFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
else:
formset = ezMapFormSet(queryset=ezMap.objects.filter(map_name ='first test'))
return render_to_response("ezmapping/manage_mapOptions.html", {'formset': formset,})
模板:
<html>
<head>
<title>Manage Map Options</title>
</head>
<body>
<h1>Define map options</h1>
<form method="post" action="">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form.as_p }}
{% endfor %}
<input type="submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:3)
您需要使用RequestContext
来使用CSRF标记。
https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
context = RequestContext(request, {
'foo': 'bar',
})
# or
render_to_response('foo.html', {}, context_instance=RequestContext(request))
RequestContext
接受请求对象并自动加载各种变量,包括CSRF。