how to save image in Django project

  Kiến thức lập trình

when i try to create new employee in my project the instance has been save but image not.

here is my model,view and form from my django project
my model-

`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',)`

my view-

   `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})`

my 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'}),
    }`

when i try to creat new employee in my django project, new employee has been created but image has not been saved.what should i do?

New contributor

Aghontok is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT