我有以下型号:
class Business(models.Model):
business_name = models.CharField(max_length=100)
def __str__(self):
return self.business_name
class Employee(models.Model):
employee_name = models.CharField(max_length=100)
business = models.ForeignKey(Business, blank=True)
我正在尝试为用户输入一个表单以输入员工。每个用户只有一个业务,每个业务可以有多个员工。我想让表单保存员工和公司名称。我设法让表单显示员工的文本字段,并下载hte商家名称。但是,当窗体在视图中由以下代码处理时,它不会向员工保存指向业务的链接 - 即使在下拉菜单中选择了业务,业务也会显示为空。
def business_home(request):
b = Business.objects.get(business_name='Cleaners')
context_dict = {
'employee_name_form': EmployeeNameForm(initial={'business': b})}
if request.method == 'POST':
form = EmployeeNameForm(data=request.POST)
if form.is_valid():
print(form.cleaned_data)
print(form.save())
w = form.save()
w.business.save()
w.save()
虽然当我打印出表单中的已清理数据时,很明显它正在读取员工和业务数据,而form.save()返回我想写入数据库的对象 - - 与正确业务挂钩的员工。
知道它为什么不能保存?
这是我的表格:
class EmployeeNameForm(forms.models.ModelForm):
class Meta:
model = Employee
fields = ('employee_name', 'business')
widgets = {
'employee_name': forms.fields.TextInput(attrs={
'placeholder': 'Enter the name of the employee you wish to add',
'class': 'form-control input-lg',
}),
}
def __init__(self, *args, **kwargs):
super(EmployeeNameForm, self).__init__(*args, **kwargs)