Upload Image with Django Model Form

Posted by jmitchel3 on Stack Overflow See other posts from Stack Overflow or by jmitchel3
Published on 2012-10-30T22:23:59Z Indexed on 2012/10/30 23:01 UTC
Read the original article Hit count: 432

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!

© Stack Overflow or respective owner

Related posts about django

Related posts about django-imagefield