我正在使用模型表單一次添加模型的多個實例。我正在使用基於類的視圖。這是我創建「庫」modelformset_factory和csrf標記丟失或不正確
class LibraryCreate(View):
model = Library
def post(self, request, *args, **kwargs):
LibraryFormSet = modelformset_factory(
Library, form=create_library, extra=2)
if request.method == 'POST':
formset = LibraryFormSet(request.POST, request.FILES)
if formset.is_valid():
# do something with the formset.cleaned_data
pass
else:
formset = LibraryFormSet()
return render_to_response(
'trial1/library_form.html', {'formset': formset})
def get(self, request, *args, **kwargs):
LibraryFormSet = modelformset_factory(
Library, form=create_library, extra=2)
formset = LibraryFormSet(queryset=Library.objects.none())
return render_to_response(
'trial1/library_form.html', {'formset': formset})
views.py一部分,這是我的模板
<form method="post" action="{% url "library_create" %}">
{% csrf_token %}
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
<input type="submit" value="create" />
現在由於某種原因,當我嘗試提交它返回一個形式403因爲「CSRF令牌丟失或不正確」而被禁止。我不明白爲什麼這不起作用,它變得非常令人沮喪。
你有CSRF中間件裝? django.middleware.csrf.CsrfViewMiddleware – professorDante
middleware已經在settings.py @professorDante – user3567826