我正在使用Django 1.11
我已创建Form
并使用Class based view
创建记录并保存到数据库。
商家/ models.py
class BusinessType(models.Model):
title = models.CharField(max_length=100)
created = models.DateTimeField('date created', auto_now_add=True)
modified = models.DateTimeField('last modified', auto_now=True)
class Meta:
db_table = 'business_types'
def __str__(self):
return self.title
class Business(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)
created = models.DateTimeField('date created', auto_now_add=True)
modified = models.DateTimeField('last modified', auto_now=True)
class Meta:
verbose_name = 'business'
verbose_name_plural = 'businesses'
db_table = 'businesses'
def __str__(self):
return self.name
商家/ Forms.py
class BusinessForm(ModelForm):
class Meta:
model = Business
fields = ['user']
商家/ views.py
class BusinessCreate(LoginRequiredMixin, CreateView):
model = Business
form = BusinessForm
def form_valid(self, form):
messages.success(self.request, 'form is valid')
form.instance.user = self.request.user
form.save()
def get_success_url(self):
messages.success(self.request, 'Business Added Successfully')
return reverse('business:list')
在加载BusinessCreate
的模板时,它会出现错误
使用没有'字段的ModelFormMixin(BusinessCreate的基类)'属性被禁止。
我的试用
将fields
移至views class
后,工作正常。但我不想这样做,因为我可能在多个视图上使用此表单,因此将来需要在多个页面上进行更改。
答案 0 :(得分:5)
您的表单未被识别。这是因为您已使用form
在视图中设置属性,但正确的属性为form_class
。
(注意,如果您正确设置了form_class
,那么您也不需要model
。)
答案 1 :(得分:0)