Django multiple forms one submit - CSRF verification failure -
this continuation of previous post attempted submit multiple forms @ once, using 1 submit button. tried resolve issue in comment section, did not succeed.
the code appears fine, however, reason 403
error (csrf verification failed. request aborted). moreover, in command prompt:
userwarning: {% csrf_token %} used in template, context did not provide value. caused not using requestcontext. "a {% csrf_token %} used in template, context "
could please assist me in figuring out problem is?
django version 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 -*- django.shortcuts import render_to_response django.template import requestcontext django.http import httpresponseredirect django.core.urlresolvers import reverse myproject.myapp.models import document myproject.myapp.forms import documentform myproject.myapp.forms import documentform2 django.shortcuts import render 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 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 list page documents = document.objects.all() # render list page documents , form return render(request, 'list.html', {'documents': documents, 'form': form, 'form2': form2})
forms.py
# -*- coding: utf-8 -*- django import forms class documentform(forms.form): docfile = forms.filefield( label='select file' ) class documentform2(forms.form): docfile2 = forms.filefield( label='select file' )
models.py
# -*- coding: utf-8 -*- django.db import models class document(models.model): docfile = models.filefield(upload_to='documents')
urls.py
# -*- coding: utf-8 -*- django.conf.urls import patterns, url urlpatterns = patterns('myproject.myapp.views', url(r'^list/$', 'list', name='list'), )
More valuable post!!! Thanks for sharing this great post with us.
ReplyDeleteWhy is Java So Popular?
Why Java?