我想在用户提交创建表单时自动将公司名称呈现到数据库中。
这是我的模特
class company(models.Model):
User = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True)
Name = models.CharField(max_length=50,blank=False)
class group1(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
group_Name = models.CharField(max_length=32)
Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_group')
这就是我在views.py中试图做的事情
class group1CreateView(LoginRequiredMixin,CreateView):
form_class = group1Form
template_name = "accounting_double_entry/group1_form.html"
def form_valid(self, form):
form.instance.User = self.request.user
form.instance.Company = company
return super(group1CreateView, self).form_valid(form)
但是出现此错误:
ValueError: Cannot assign "<class 'company.models.company'>": "group1.Company" must be a "company" instance.
它适用于用户,但不适用于公司。
谁能告诉我我在这件事上做错了吗?
谢谢...
答案 0 :(得分:4)
错误可能在此行
form.instance.Company = company
这里的 company
看起来像是Python class
,它应该是company
类的实例
因此,使用一个对象/实例作为
company_obj = company.objects.create(.....) # created a ne object
form.instance.Company = company_obj
OR
company_obj = company.objects.get(id=someid) # fetch new object from db
form.instance.Company = company_obj
除了上述建议外,我们建议您在代码/项目中遵循PEP8 naming convetions
答案 1 :(得分:2)
使用查询来代替您需要的公司对象,而不是c=company.objects.get(id=1)
。
def form_valid(self, form):
form.instance.User = self.request.user
c=company.objects.get(id=1)
form.instance.Company = c
return super(group1CreateView, self).form_valid(form)
答案 2 :(得分:2)
@JPG的答案是正确的。我将详细解释。
首先,您错误地输入了您的班级名称。类名在CamelCase之后,Python中的首字母大写。违反此规定将导致类似这样的错误,您将类名与实例名混淆。
答案 3 :(得分:2)
您需要这样的内容:
class group1CreateView(LoginRequiredMixin,CreateView):
form_class = group1Form
template_name = "accounting_double_entry/group1_form.html"
def form_valid(self, form):
form.instance.User = self.request.user
# form.instance.Company = company
form.instance.Company = company.objects.get(pk='something') # OR
# form.instance.Company = company.objects.create(stuff='stuff')
return super(group1CreateView, self).form_valid(form)
另外,类名称应以大写(Pascal Case)开头,其属性应以小写(snake_case)开头。这是一种常见的做法,请遵循以免造成混淆