表单发布后django ImageField为空

时间:2016-11-29 20:50:47

标签: django django-forms django-views

当我通过表单将照片上传到django时,图片字段为空。我使用logging.info(form.cleaned_data['picture'] )

确认了这一点

我通过控制台检查了表单是否有'multipart/form-data'

模特:

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

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)

html模板:

<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>

1 个答案:

答案 0 :(得分:1)

我可能错了,但据我所知,参数“multipart / form-data”应该在表单中,而不是在输入中,并将它安装到FieldFile

'picture': forms.FileInput(attrs={'required': False,'class': 'form-control','enctype': 'multipart/form-data'}),