[Django]-Django Image Upload Form not valid

4👍

If you form class is a modelform: class ImageForm(forms.ModelForm): you can pass the instance to the form and save it.

def display_update_image(request, pk):
    if request.method == 'POST':
        display = Display.objects.get(pk = pk)
        form = ImageForm(request.POST, request.FILES, instance=display)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(reverse('displays'))
    else :
        form = ImageForm()
    return render(request, 'catalog/update_display_image.html', {'form': form})

0👍

In forms.py check that you have a Django Form like this one:

class ImageForm(forms.ModelForm):
    class Meta:
        model = Display
        fields = ['image',]

In template add {{ form }} instead of manually using input, like this one:

<form method='post' enctype='multipart-formdata>
{% csrf_token %}
{{ form }}
<input type='submit' value='Update Image'>

Leave a comment