禁止在没有 'fields' 属性的情况下使用 ModelFormMixin

Using ModelFormMixin without the 'fields' attribute is prohibited

我正在使用 Django 1.11

我创建了 Form 并使用 Class based view 创建记录并保存到数据库。

Business/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

Business/Forms.py

class BusinessForm(ModelForm):
    class Meta:
        model = Business
        fields = ['user']

Business/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 的模板时出现错误

禁止在没有 'fields' 属性的情况下使用 ModelFormMixin(BusinessCreate 的基础 class)。

我的试炼

fields 移动到 views class 后,它工作正常。但我不想这样做,因为我可能会在多个视图上使用此表单,因此如果需要,将来需要在多个页面上进行更改。

无法识别您的表单。这是因为您在视图中使用 form 设置了属性,但正确的属性是 form_class.

(请注意,如果您正确设置了 form_class,您也不需要 model。)

对我来说,它是通过像这样添加字段变量来修复的

model = xxxxxxxxxx fields = '__all__'

模型名称后

参考这个url