Using ModelFormMixin without the 'fields' attribute is prohibited

Anuj TBE picture Anuj TBE · Oct 12, 2017 · Viewed 14.4k times · Source

I'm using Django 1.11

I have created a Form and using Class based view to create a record and save to database.

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')

On loading template of BusinessCreate it gives error as

Using ModelFormMixin (base class of BusinessCreate) without the 'fields' attribute is prohibited.

My Trials

After moving fields to views class, it is working fine. But I don't want to do so, as I may be using this form on multiple views and thus will require changes on multiple pages in future if needed.

Answer

Daniel Roseman picture Daniel Roseman · Oct 12, 2017

Your form is not being recognised. This is because you have used form to set the attribute in the view, but the correct attribute is form_class.

(Note, if you correctly set form_class, you don't need model as well.)