[Django]-Django Form not rendering

0👍

Change the name of the forms in the view. It now looks like this

form = ContractForm(user=request.user)

And it works.

👤Dean

2👍

The queryset argument to forms.ModelChoiceField should be a queryset. It should read:

self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user=user))

And you have to declare it in your form first before overriding it in the __init__() method:

class ContractForm(forms.Form):
    ...
    client = forms.ModelChoiceField(queryset=Client.objects.all())
👤Arnaud

2👍

There are quite a few things wrong here, in addition to the QuerySet issue Arnaud points to.

Firstly, when you instantiate the form in response to a GET, you do contractForm = ContractForm(user). But the first parameter to a form instantiation (as you correctly do in the POST) is the posted data – and you haven’t altered the form’s __init__ signature.

Secondly, in the __init__ itself, you reference a user variable: but you haven’t actually got that variable from anywhere. You can’t magically reference variables without receiving them from somewhere.

So to fix those errors, you need to change the init method as follows:

def __init__(self, *args, **kwargs):
    user = kwargs.pop('user')
    super(ContractForm, self).__init__(*args, **kwargs)
    self.fields['client'].queryset=Client.objects.filter(user=user)

and instantiate the form in the view like this:

contractForm = ContractForm(user=request.user)

Thirdly, although this is not related to the problem you post, you will never see any errors on this form, because you don’t check it is valid in the POST section – you need to check if contractForm.is_valid(), and if not fall through to the final render_to_response (which needs to be unindented one level).

Also, you are ignoring the whole point of having a form, by setting your model direct from request.POST. You should be using the contents of contractForm.cleaned_data to create the Contract instance.

And finally, you should investigate whether a ModelForm would meet your needs better.

Leave a comment