当我尝试感觉部门领域显示此错误时。 我不明白此错误。.请帮帮我
class Department(models.Model):
name = models.CharField(max_length= 20,null=True)
def __str__(self):
return self.name
class Employee(models.Model):
employee_name = models.CharField(max_length= 20, null=True)
surname = models.CharField(max_length= 20, null=True)
address = models.CharField(max_length = 50, null=True)
qualification = models.CharField(max_length = 30,null=True)
contact_num = models.IntegerField(null=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
def __str__(self):
return self.employee_name
这是我的模型。py
class AdForm(forms.ModelForm):
employee_name = forms.CharField()
surname = forms.CharField ()
address = forms.CharField ()
qualification = forms.CharField ()
contact_num = forms.IntegerField ()
department = forms.CharField()
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
这是我的表格。py
def create(request):
if request.method == 'POST':
form = AdForm(request.POST)
if form.is_valid(): #getting error on this
form.save()
return HttpResponseRedirect(reverse('employee-list'))
else:
form = AdForm()
return render(request, 'employee/create.html', {'form': form})
这是我的view.py
{{1}}
答案 0 :(得分:3)
department
模型上的Employee
字段是ForeignKey
字段,但是在AdForm
中,您将其定义为CharField
。
您可以在表单中修复字段定义。另外,您也可以简单地删除显式字段定义。使用模型表单时,Django将为您选择正确的字段类型。
class AdForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
这会将部门字段呈现为<select>
小部件,使您可以从(现有)部门中进行选择。