Enchantner
Enchantner

Reputation: 1554

How to upload photo into UserProfile for specified user in django?

I have a photo field in my UserProfile model, so any user is able to upload his photo. I was thinking that all I need is ModelForm for the UserProfile, but without User specified it will fail, of course. But if I pass the request.user as a parameter into a form constructor - it won't work, too, because of the thing that form's UserProfile isn't connected with this user.

class ProfileUploadPhotoForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('photo',)

Is there any way to set, which user's profile to modify?

Upvotes: 0

Views: 532

Answers (2)

Enchantner
Enchantner

Reputation: 1554

Problem solved! I forgot to add

enctype="multipart/form-data"

in form attributes.

Upvotes: 0

You need to pass it an instance of a UserProfile to update.

uploadform = ProfileUploadPhotoForm(request.POST, request.FILES,\
    instance=request.user.userprofile)

if uploadform.is_valid():
    uploadform.save()

Upvotes: 1

Related Questions