当我尝试感觉部门字段显示此错误时。
我不明白此错误..请帮帮我
Cannot assign "'HR'": "Employee.department" must be a "Department" instance.
这是我的模型
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
这是我的form.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')
这是我的view.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})
最佳答案
department
模型上的Employee
字段是ForeignKey
字段,但是在AdForm
中将其定义为CharField
。
您可以在表单中修复字段定义。另外,您也可以简单地删除显式字段定义。使用模型表单时,Django将为您选择正确的字段类型。
class AdForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
这会将部门字段呈现为
<select>
小部件,使您可以从(现有)部门中进行选择。关于python - 无法分配“HR”:“Employee.department”必须是“Department”实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51019461/