Reputation: 143
When I upload a photo to django through form the image field is empty. I confirmed this by using logging.info(form.cleaned_data['picture'] )
I checked through the console that the form has 'multipart/form-data'
The model :
class Person(models.Model):
user = models.ForeignKey(User, default=1)
name = models.CharField(max_length=250,null=True)
last_name = models.CharField(max_length=500)
treatment_plan=models.CharField(max_length=256,null=True,blank=True)
treatment_done=models.CharField(max_length=256,null=True,blank=True)
picture = models.ImageField(upload_to='image', storage=DEFAULT_FILE_STORAGE,blank=True)
def __str__(self):
return self.name
the modelForm :
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['name', 'last_name', 'age', 'martial_status', 'mobile', 'sex',
'amount_paid','amount_left','note', 'address','date','picture','treatment_done','treatment_plan','chief_complain']
widgets = {
'name': forms.TextInput(attrs={'required': True, 'class': 'form-control',
'placeholder': 'name'}),
'last_name': forms.TextInput(attrs={'required': True, 'class': 'form-control',
'picture': forms.FileInput(attrs={'required': False,'class': 'form-control','enctype': 'multipart/form-data'}),
view.py :
def add_person(request):
if not request.user.is_authenticated():
return render(request, 'core/login.html')
else:
form = PersonForm(request.POST or None,request.FILES or None,instance=Person())
#form = PersonForm(request.POST or None,request.FILES )
if form.is_valid():
persons = form.save()
persons.user = request.user
#to capitalized the first letter so we have consistency when querying , this is a workaround since __iexact is not working
persons.name=persons.name.title()
persons.last_name=persons.last_name.title()
logging.info(form.cleaned_data['last_name'] )
persons.save()
return redirect('home')
context = {
"form": form,
}
return render(request, 'core/add_person.html', context)
The html template :
<div class="col-sm-4 form-group">
<label for="address">{% trans "Address" %}</label>
{{ form.address|add_class:"form-control" }}
</div>
<div class="col-sm-4 form-group">
<label for="pic">{% trans "Picture" %}</label>
{{form.picture}}
</div>
Upvotes: 1
Views: 1676
Reputation: 138
I may be wrong, but still, as far as I know the parameter "multipart/form-data" should be in the form, and not in input, and you install it to the FieldFile
'picture': forms.FileInput(attrs={'required': False,'class': 'form-control','enctype': 'multipart/form-data'}),
Upvotes: 1