Django: Why is the Image Field not working

Good day,

I am testing some stuff with Django image Fields and the user model. The point is simply that any user can upload and update a profile picture. But when I select a picture and press upload, I get the message 'This field is required. So it's as if I haven't selected anything.

\\photo.html

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Upload</button>
</form>

\\views.py

def photo_view(request):
    try:
        profile = request.user.userimage
    except UserImage.DoesNotExist:
        profile = UserImage(user=request.user)

    if request.method == 'POST':
        form = UserImageForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('/dashboard/user/profile')
    else:
        form = UserImageForm(instance=profile)

    return render(request, 'photo.html', {'form': form})

\models.py

class UserImage(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE)
    photo = models.ImageField(
        upload_to='images/', height_field=None, width_field=None, max_length=100)

    def __str__(self):
        return str(self.user)

\\settings.py

MEDIA_ROOT =  os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I tried it with this one https://www.geeksforgeeks.org/imagefield-django-models/

Do someone know a solution? Or should I even use the ImageField when working with images?

Thank you very much! :-)


There are two problems here: if you upload files, you need to specify enctype="multipart/form-data":

form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Upload</button>
</form>

furthermore you need to pass both request.POST and request.FILES to the form:

def photo_view(request):
    try:
        profile = request.user.userimage
    except UserImage.DoesNotExist:
        profile = UserImage(user=request.user)
    
    if request.method == 'POST':
        form = UserImageForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('/dashboard/user/profile')
    else:
        form = UserImageForm(instance=profile)

    return render(request, 'photo.html', {'form': form})