3

In my app I allow users to have a profile picture. And I would like them to be able to change it. Surprisingly, I didn't find anything on how to accomplish that.

Here is what I tried:

models.py

        class UserProfile(FacebookProfileModel):
           user = models.OneToOneField(User)
           profilepic = models.ImageField(upload_to="profilepics/", default="blabla.jpg")

my html:

       <form method='post' action='{%url myproject.views.changes %}>
       <div class="controls">
       <input type="file" name="image">
       </div>
       <input type="submit">
       </form>

my view:

      def changes(request):
          if 'image' in request.POST:
             image = request.POST.get('image')
             userprofile.profilepic.url = image
             userprofile.save()

When I do that, I get the following error message:

       'AttributeError at /my/site/
        can't set attribute'

Any idea on how I could accomplish that? Thank you

Juliette Dupuis
  • 1,027
  • 2
  • 13
  • 22

2 Answers2

2

Make sure you request a UserProfile object first, then

Looks like you should use

image = request.FILES['image']
userprofile.profilepic = image

instead of

image = request.POST.get('image')
userprofile.profilepic.url = image

See This example, the views.py section, as Jake said

Community
  • 1
  • 1
TimDC
  • 121
  • 3
  • 11
1

You need to include enctype="multipart/form-data" in your form. Here is an example of how to update an ImageField:

first the update_form.html:

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Update</button>
</form>

Then the form:

from django.contrib.auth import get_user_model


class EditProfile(UserChangeForm):
    class Meta:
        model = get_user_model()
        fields = ('email', 'name', 'avatar')

And finally the view:

def user_edit(request):
    if request.method == 'POST':
        form = EditProfile(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            if request.FILES.get('avatar', None) != None:
                try:
                    os.remove(request.user.avatar.url)
                except Exception as e:
                    print('Exception in removing old profile image: ', e)
                request.user.avatar = request.FILES['avatar']
                request.user.save()
            return redirect('user:profile', id=request.user.id)
    else:
        form = EditProfile(instance=request.user)
        return render(request, 'user/user-edit.html', {'form': form})
therealak12
  • 1,178
  • 2
  • 12
  • 26