Django Imagefield not working properly via ModelForm


I'm certain I'm doing something really obviously stupid, but I've been trying to figure it out for a few hours now and nothing is jumping out at me.

I'm using a ModelForm so I can expose a few fields from a model for editing. 2x ImageField, 1x TextField. The Form is processed and the TextField works. The two ImageFields do not work and they're why I'm here today.

I'm using Django 1.0.2

Here's the relevant code (ask if you need more — and I'm not including the HTML because that part appears to work fine):


class Company(models.Model):
    logo = models.ImageField(upload_to='logos', blank=True)
    intro_pic = models.ImageField(upload_to='intropics', blank=True)
    intro_text = models.TextField(blank=True)

View and form:

def admin_edit(request, company_slug):
    company = get_object_or_404(Company, slug = company_slug)

    f = AdminEditForm(instance = company)
    if request.method == 'POST':
        f = AdminEditForm(request.POST, instance = company)
        if f.is_valid():
            print "Processing form"
            print f.cleaned_data['intro_pic']

    return render_to_response('uadmin/edit.html', {'company':company, 'f':f}, RequestContext(request))

class AdminEditForm(ModelForm):
    class Meta:
        model = Company
        fields = ['logo', 'intro_pic', 'intro_text']

Best Solution

Well I feel like an idiot. In order for Django to be able to process uploaded files, you need to pass the request.FILES variable to the form (makes sense, right?!)

In my case the following line goes from:

f = AdminEditForm(request.POST, instance = company)


f = AdminEditForm(request.POST, request.FILES, instance = company)

Another thing to check (if you run into something like this in the future) is that your form is multipart. Your <form> tag should look something like this:

<form enctype="multipart/form-data" method="post" action="">
Related Question