Upload Image with Django Model Form

jmitchel3 picture jmitchel3 · Oct 30, 2012 · Viewed 11.6k times · Source

I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access.

#Models.py
class Profile(models.Model):
    name = models.CharField(max_length=128)
    user = models.ForeignKey(User)
    profile_pic = models.ImageField(upload_to='img/profile/%Y/%m/')

#views.py
def create_profile(request):
    try: 
        profile = Profile.objects.get(user=request.user)
    except:
        pass
    form = CreateProfileForm(request.POST or None, instance=profile)

    if form.is_valid():
       new = form.save(commit=False)
       new.user = request.user
       new.save()

return render_to_response('profile.html', locals(), context_instance=RequestContext(request))


#Profile.html
<form enctype="multipart/form-data" method="post">{% csrf_token %}
<tr><td>{{ form.as_p }}</td></tr>
<tr><td><button type="submit" class="btn">Submit</button></td></tr>
</form>

Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help!

Answer

Aidas Bendoraitis picture Aidas Bendoraitis · Oct 30, 2012

You need to pass request.FILES to your form:

form = CreateProfileForm(request.POST, request.FILES, instance=profile)

Ref: Handling uploaded files with a model