-
-
Save Greymalkin/9232287 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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 %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
url(r'^banner/upload/$', 'banners.views.upload_banner', name='upload-banner') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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