I am currently using forms.Form type for one of my forms because I needed to specify many parameters for them, such as queryset, disabled, required.

Snippet of the parameters I am talking about in my forms.py

class InputClassInformation(forms.Form):
    module = forms.ModelChoiceField(queryset=Module.objects.all())
    title = forms.CharField(disabled=True, required=False)

The form will allow users to update certain fields in an entry, that means I will have to use the instance parameter as seen in here https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#the-save-method . However, I get this error when I run my code in views.py

if Class.objects.filter(module__subject=subject).exists():
   a = Class.objects.filter(module__subject=subject)[0].pk
   form = InputClassInformation(request.POST, instance=a)

Error:

TypeError at /input-class-info/
__init__() got an unexpected keyword argument 'instance'

I know this would have been fine if I was using ModelForm, but trying to specify all the parameters I need in ModelForm has been difficult, so is there a way I can specify the instance I want to update while using forms.Form?

1 Answers

0
IceTea On Best Solutions

I'm not sure if this is a silly question since I couldn't find the answer, so I'll post an answer just to complete this anyway.

As @DanielRoseman mentioned in the question, we can instantiate the same fields by using the same code in ModelForms. In my case I simply changed my form to:

class InputClassInformation(forms.ModelForm):
    class Meta:
        model = Class
        fields = '__all__'
    module = forms.ModelChoiceField(queryset=Module.objects.all())
    title = forms.CharField(disabled=True, required=False)

and now I can use instance!