I'm working on a project where my current task is to allow users to upload new images. I edited the code from a tutorial I found here: Need a minimal Django file upload example. I initially followed the tutorial, just changed "file" to "image" since I'm only allowing image uploads, and that works fine. Then, I tried to fold it into an existing Django project, and I got to my problem: Although I have included all the error blocks, I don't get any error messages when I try to upload something that's not an image. I have included the ability to mark an image as "public", but even when I take that out, the error messages don't show up. In order to make this work with the rest of the project, I've had to split up things up more than they were in the tutorial, and I'm wondering if that's the issue.
Relevant code from the project below.
Template
<form action="{% url "upload_image" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.imagefile.label_tag }} {{ form.imagefile.help_text }}</p>
<p>
{{ form.imagefile.errors }}
{{ form.imagefile }}
</p>
<p> {{ form.errors }}</p>
<p>{{ form.public }} {{ form.public.label }}</p>
<p><input type="submit" value="Upload" /></p>
</form>
Forms
(I have two forms here because I couldn't figure out how to check the value of the checkbox otherwise.)
class ImageForm(Form):
imagefile=ImageField(label="Select image to upload.")
public=BooleanField(label="Public image", required=False)
class PublicImageForm(ImageForm):
public=BooleanField(label="Public image", required=True)
View to render the page which holds the form
def upload_image_view(request):
if request.method=='GET':
form=ImageForm()
# TODO: Limits to images uploaded by current user
my_images = UploadedImage.objects.filter(owner=User.objects.get(username=request.user))
return render_to_response(
'uploader.html',
{'my_images': my_images, 'form': form,},
context_instance=RequestContext(request))
else:
return HttpResponseNotAllowed(['GET'])
View which receives form
def upload_new_image(request):
if request.method=='POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
u= User.objects.get(username=request.user)
form = PublicImageForm(request.POST, request.FILES)
if form.is_valid():
newdoc = UploadedImage(imagefile = request.FILES['imagefile'], owner=u, isPublic=True)
else:
newdoc = UploadedImage(imagefile = request.FILES['imagefile'], owner=u, )
newdoc.save()
# else:
# form = ImageForm()
return HttpResponseRedirect('/workspace/upload_image/')
else:
return HttpResponseNotAllowed(['POST'])
Model
class UploadedImage(models.Model):
imagefile=models.ImageField(upload_to="user_images/uploaded_images")
owner=models.ForeignKey(User)
isPublic=models.BooleanField(default=False)