如何在Django项目中保存图像

问题描述 投票:0回答:1

当我尝试在项目中创建新员工时,实例已保存,但图像未保存。

这是我的 django 项目中的模型、视图和表单 我的模特-

`class Emp(models.Model):
emp_first_name=models.CharField(max_length=20,null=False)
emp_last_name=models.CharField(max_length=20,null=False)
emp_father_name=models.CharField(max_length=15,blank=False,default='')
emp_mother_name=models.CharField(max_length=15,blank=False,default='')
emp_photo=models.ImageField(null=True,blank=True,upload_to='static/image/emp',)`

我的看法-

   `def EmpAdd(request):
       if request.method=='POST':
          form=EmpForm(request.POST,request.FILES)
      if  form.is_valid():
          form.save()
           messages.success(request,'New Employee has been added')
        else:
           messages.error(request,'There has been error')
      else:
      form=EmpForm()

  return render(request,'emp/emp_crt.html',{'form':form})`

我的表格-

  `class  EmpForm(ModelForm):
     class Meta:
      model=Emp
     fields='__all__'
     widgets={
     'emp_id':TextInput(attrs={'class':'form-control',}),
     'emp_bod':DateInput(attrs={'type':'date','class':'form-control',}),
     'emp_first_name':TextInput(attrs={'class':'form-control',}),
     'emp_last_name':TextInput(attrs={'class':'form-control',}),
     'emp_father_name':TextInput(attrs={'class':'form-control'}),
     'emp_mother_name':TextInput(attrs={'class':'form-control'}),
     'emp_photo':FileInput(attrs={'class':'form-control'}),
    }`

当我尝试在 django 项目中创建新员工时,新员工已创建,但图像尚未保存。我该怎么办?

django
1个回答
0
投票

您发布的代码没有任何问题。虽然,您错过了

template
文件,但这就是问题所在。一个很常见的错误,在你的 html 表单上缺少
enctype

<form action="{% url 'reverse-url' %}" method="POST" enctype="multipart/form-data">
    {%csrf_token%}
    {{form.as_p}}
    <button type="submit">submit</button>
</form>

没有它,文件数据不会附加到表单中。

© www.soinside.com 2019 - 2024. All rights reserved.