I'm trying to upload the image file using Django. I'm able to get the other form data but not the image file. request.FILES is blank. Below is my code.
models.py
class Module(models.Model):
title = models.CharField(max_length = 50)
slug = models.CharField(max_length = 50)
description = models.TextField(max_length = 500)
Forms.py
class ModuleAddForm(forms.ModelForm):
title = forms.CharField(max_length = 50, widget = forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Title'} ))
description = forms.CharField(max_length = 50, widget = forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Description'} ))
image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)
class Meta:
model = Module
fields = ['title', 'description', 'image']
Views.py
form = ModuleAddForm(request.POST, request.FILES or None)
if form.is_valid():
title = form.cleaned_data['title']
description = form.cleaned_data['description']
image = request.FILES['image]
Html
<form class="kt-form" method = "POST" id="kt_form userform" enctype=”multipart/form-data” >{% csrf_token %}
<div class="form-group row">
<label class="col-3 col-form-label">Title</label>
<div class="col-9">
{{ form.title }}
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label">Description</label>
<div class="col-9">
{{ form.description }}
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label">Image</label>
<div class="col-9">
{{ form.image }}
</div>
</div>
<button type="submit" class="btn btn-brand">Save</button>
</form>
When I print request.FILES it returned blank and also when I tried to get it using Key it returned MultiValueDict error. But when I print request.POST, image was there. But it was of no use because an image wasn't uploaded.
I'm using another model to store the image files of this model (Module) because it can contain multiple images. I've implemented the same logic in my other model and function. It's working there properly but not working here.
I'm using Django 2.2.
action
form attribute. - Nishant Nawarkhede