Uploading image files
Asked Answered
L

3

9

Could you please help me to get image upload working on a view with django forms?

Models.py

class User_Profile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='profile')
    photo  = models.ImageField(upload_to = 'profiles/', null=True, blank=True)

Forms.py

class ProfileForm(forms.ModelForm):
        class Meta:
            model = User_Profile
            exclude = ('user')

Views.py

    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, instance=request.user.profile)

        if profile_form.is_valid():
            profile_form.save()
            return HttpResponseRedirect('/panel/correct/')

    else:
        profile_form = ProfileForm(instance=request.user.profile)

My html form already contains enctype="multipart/form-data"

Linseylinseywoolsey answered 3/7, 2009 at 10:34 Comment(1)
Hi Alex, you might have to tell us what's not working for you at present.Lorylose
S
16

You don't seem to be binding the file data to the form.

profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) 
Smatter answered 3/7, 2009 at 11:11 Comment(1)
Thanks, that was the problem... This is the first time I use Forms in Django... (not using django since 0.96 without newforms)Linseylinseywoolsey
H
7

Why not use the django-avatar project (I'm assuming you are thinking of adding user avatars to your project, based on the example)?

They have a pretty neat solution with an extra tag that resizes the image before displaying it first time. You store the original image and define the image sizes that you wish to accept on the website and the rest is done automagically for you.

Hofmannsthal answered 3/7, 2009 at 10:53 Comment(0)
E
3

This is just a matter of following the docs.

You are not using the correct form initialization in your post. In particular you are missing request.FILES parameter:

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

after the above the uploaded file can be retrieved from the FILES array:

 photo_file = request.FILES['photo']
Elissaelita answered 3/7, 2009 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.