ailinmc
ailinmc

Reputation: 77

Editing image field using Django forms

I am currently creating an application that allows users to view and edit their own personal profile. I've recently added in the ability for a user to add a profile picture to their profile. I can add a profile in the admin page and it will show up on the selected users profile no problem. The problem is when the user tries to update their picture I am getting an ValueError telling me that the image attribute has no file associated. Below is how I have tried to implement the functionality.

Models

class UserProfileModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.PositiveIntegerField(blank=True, null=True)
    email = models.EmailField(max_length=254, null=True, blank=True, unique=True)
    height = models.PositiveIntegerField(blank=True, null=True)
    weight = models.PositiveIntegerField(blank=True, null=True)
    bio = models.CharField(max_length=100, blank=True, default='')
    image = models.ImageField(upload_to='profile_image', blank=True)

forms

class UpdateProfile(forms.ModelForm):

    class Meta:
        model = UserProfileModel
        fields = ('email', 'age', 'height', 'weight', 'bio', 'image')

views

def update_profile(request):
    args = {}

    if request.method == 'POST':
        form = UpdateProfile(request.POST, instance=request.user.userprofilemodel)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('account:profile'))
            # return render(request, 'account/profile.html')
    else:
        form = UpdateProfile()
        if request.user.is_authenticated():
            form = UpdateProfile(instance=request.user.userprofilemodel)
        args['form'] = form
        return render(request, 'account/edit_profile.html', args)

HTML

<!DOCTYPE html>
<html>
<body>

{#<h2 style="text-align:center">User Profile Card</h2>#}

<div class="container">
  <h1>{{ user }}s Profile </h1>
  <div style="margin: 24px 0;">
        <p>Username: {{ user }}</p>
        <p>Email: {{ user.userprofilemodel.email }}</p>
        <p>Age: {{ user.userprofilemodel.age }}</p>
        <p>Height: {{ user.userprofilemodel.height }} CM </p>
        <p>Weight: {{ user.userprofilemodel.weight }} KG </p>
        <p>User Bio: {{ user.userprofilemodel.bio }} </p>
        <img src="{{ user.userprofilemodel.image.url }}" width="240">


</body>
</html>

Upvotes: 2

Views: 3587

Answers (1)

Will Keeling
Will Keeling

Reputation: 22994

Looks like you may have forgotten to pass request.FILES to your form?

form = UpdateProfile(request.POST, request.FILES, instance=request.user.userprofilemodel)

Also, you haven't shown the template containing the form used to upload an image, but ensure that the form's enctype is set to multipart/form-data.

<form method="post" enctype="multipart/form-data">

Upvotes: 3

Related Questions