Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Image with Django Model Form

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!

like image 401
jmitchel3 Avatar asked Oct 30 '12 22:10

jmitchel3


People also ask

How do I store images in Django?

In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory. The list_display list tells Django admin to display its contents in the admin dashboard.


2 Answers

You need to pass request.FILES to your form:

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

Ref: Handling uploaded files with a model

like image 180
Aidas Bendoraitis Avatar answered Sep 23 '22 04:09

Aidas Bendoraitis


Form initialization code have to be like this:

form = MemberSettingsForm(request.POST or None, request.FILES or None, instance=user)
like image 29
Denti Avatar answered Sep 25 '22 04:09

Denti