Django Image Upload Form not valid

Viewed 1539

For some reason in django the form that I am trying to use is not considered valid. This code is taken almost directly from a site that claims that it works but is still not functional. my code is as follows.

VIEWS

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

TEMPLATE (template name is update_display_image.html)

<form method = "post" enctype = "multipart/form-data">{% csrf_token %}
<p>
    <input id = "id" type = "file" class = "" name = "image">
</p>
<input type = "submit" value = "Submit" />

MODELS

class Display(models.Model):
    title = models.CharField(max_length = 50,)
    image = models.ImageField(upload_to = 'images')
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

    def __str__(self):
        return self.title

edit: forget to post Forms code sorry

class ImageForm(forms.Form):
    image = forms.ImageField()

further edit: changing my forms class to this

class ImageForm(forms.Form):
    class Meta:
        model = Display
        fields = ('image',)

Allows the form to be read as valid for some reason though I don't understand why. Unfortunately that causes my views method to be unable to function properly as it can no longer read

display.image = form.cleaned_data['image']
2 Answers
Related