Django多次形成一次提交 - CSRF验证失败

时间:2016-02-05 21:39:00

标签: django forms python-2.7 upload django-csrf

这是我previous post的延续,我尝试使用一个提交按钮一次提交多个表单。我试图在评论部分解决这个问题,但是我没有成功。

代码似乎没问题,但由于某些原因我收到403错误( CSRF验证失败。请求已中止)。 而且,这是我在命令提示符中得到的:

UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context "

有人可以帮我弄清问题是什么吗?

Django版本1.9.2

html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head> 
<body>
    <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        {{ form2.as_p }}
        <p><input type="submit" value="Upload"/></p>
    </form>  
 </body>  
</html>

views.py

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm
from myproject.myapp.forms import DocumentForm2
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt,csrf_protect


#@csrf_exempt <-- tried adding this, still doesn't work
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, prefix="form")
        form2 = DocumentForm2(request.POST, prefix="form2")

        if form.is_valid() or form2.is_valid():        
            newdoc = Document(docfile=request.FILES['docfile'])

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))

    else:

        form = DocumentForm(prefix="form")  
        form2 = DocumentForm2(prefix="form2")  
        #return render_to_response('list.html', {'form': form, 'form2': form2})

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form, 'form2': form2})

forms.py

# -*- coding: utf-8 -*-   
from django import forms


class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file'
        )

class DocumentForm2(forms.Form):
    docfile2 = forms.FileField(
        label='Select a file'
        )

models.py

# -*- coding: utf-8 -*-
from django.db import models


class Document(models.Model):
    docfile = models.FileField(upload_to='documents')

urls.py

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

urlpatterns = patterns('myproject.myapp.views',
    url(r'^list/$', 'list', name='list'),
)

0 个答案:

没有答案