Skip to content

Instantly share code, notes, and snippets.

@mattoc
Created November 13, 2012 10:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattoc/4065008 to your computer and use it in GitHub Desktop.
Save mattoc/4065008 to your computer and use it in GitHub Desktop.
Django: handle form validation with combined POST and FILES data
"""Allows checking of form POST data as well as uploaded files when validating
a standard Django `forms.Form`.
The short version is that you check `Form().files` in the `clean()` method,
assuming the form has been bound to the request.
See:
http://mattoc.com/django-handle-form-validation-with-combined-post-and-files-data/
"""
from django import forms
class BannerUploadForm(forms.Form):
banner = forms.FileField()
placeholder_text = forms.CharField()
def clean(self):
cleaned_data = super(BannerUploadForm, self).clean()
text = cleaned_data.get('placeholder_text')
if not text and not 'banner' in self.files:
raise forms.ValidationError('Please upload a banner image or '
'add placeholder text.')
return cleaned_data
{% extends 'base.html' %}
{% block content %}
<form method="post" action="{% url upload-banner %}" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload">
</form>
{% endblock content %}
url(r'^banner/upload/$', 'banners.views.upload_banner', name='upload-banner')
from django.shortcuts import render
from .forms import BannerUploadForm
def upload_banner(request):
template_name = 'banners/upload.html'
context = {}
if request.method == 'POST':
# request.FILES must be bound to form else form.files will be empty
form = BannerUploadForm(request.POST, request.FILES)
if form.is_valid():
# your handler here
template_name = 'banners/success.html'
else:
form = BannerUploadForm()
context['form'] = form
return render(request, template_name, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment