Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form is_valid always false

In my django application the form never returns true even if I add the same data as in the admin application. My model.py looks like:

from django.db import models
from django.db.models import ImageField, signals
from django.dispatch import dispatcher
from django.forms import ModelForm

# Create your models here.
class Image(models.Model):
    emailAddress = models.EmailField(max_length=75)
    image = ImageField(upload_to='photos')
    caption = models.CharField(max_length=100)

class UploadForm(ModelForm):
    class Meta:
        model = Image

My views.py looks like:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from competition.models import Image, UploadForm

# Create your views here.

def index(request):
    images = Image.objects.all().order_by('emailAddress')
    return render_to_response('images/index.html', {'images': images})

def uploadImage(request):
    if request.method == 'POST': # If the form has been submitted...
        form = UploadForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            emailAddress = form.cleaned_data['emailAddress']
            image = form.cleaned_data['image']
            caption = form.cleaned_data['caption']
            i = Image(emailAddress=emailAddress, image = image, caption = caption)
            i.save()
            return HttpResponseRedirect('../image/')
        else:
            return render_to_response('images/upload.html', {'form': form})
    else:
        form = UploadForm() # An unbound form
        return render_to_response('images/upload.html', {'form': form})

My template looks like:

<html>
<body>
    <form enctype="multipart/form-data" action="/image/uploadImage" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
    </form>
    </body>
</html>

I can get it work correctly if I use the admin application but need a generic form and this does't work as it keeps asking for a either the email address or image (the error appears above the image field). So why might my form not be valid?

like image 314
Dean Avatar asked Feb 22 '23 23:02

Dean


2 Answers

You need to instantiate your form with request.FILES as well as request.POST.

As an aside, you can save the model form instead of creating the Image by hand in the view.

like image 137
Alasdair Avatar answered Feb 26 '23 22:02

Alasdair


You have a required image but you aren't binding the file data to the form.

form = UploadForm(request.POST)

should be

form = UploadForm(request.POST, request.FILES)

See https://docs.djangoproject.com/en/1.3/ref/forms/api/#binding-uploaded-files

like image 23
Mark Lavin Avatar answered Feb 26 '23 20:02

Mark Lavin