I have the following view in forms.py:
class ContractForm(forms.Form):
title = forms.CharField()
start_date = forms.DateField()
end_date = forms.DateField()
description = forms.CharField(widget=forms.Textarea)
client = forms.ModelChoiceField(queryset=Client.objects.all())
def __init__(self, user, *args, **kwargs):
super(ContractForm, self).__init__(*args, **kwargs)
self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user=user))
clients = Client.objects.filter(user = user)
for client in clients:
print client
And, in my opinion, the method is as follows:
def addContract(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/contractManagement/login/?next=%s' % request.path)
else:
if request.method == 'POST':
contractForm = ContractForm(request.POST)
title = request.POST['title']
start_date = request.POST['start_date']
end_date = request.POST['end_date']
description = request.POST['description']
client = request.POST['client']
user = request.user
contract = Contract(title,start_date,end_date,description,client,user)
contract.save()
return HttpResponseRedirect('../../accounts/profile/')
else:
user = request.user
print user.username
contractForm = ContractForm(user)
return render_to_response('newcontract.html', {'contractForm': contractForm})
But the form will not be displayed in the browser. All that is displayed is the submit button. My HTML looks like this:
<html>
<head>
</head>
<body>
{% if contractForm.errors %}
<p style="color: red;">
Please correct the error{{ contractForm.errors|pluralize }} below.
</p>
{% endif %}
<form method="POST" action="">
<table>
{{ contractForm.as_table }}
</table>
<input type="submit" value="Submit" />
</form>
</body>
</html>
So why the form will not be displayed?
EDIT
I got rid of the user field of the client requiring the user, and it still will not be displayed. I thought this might help. Thus, a form can use this class:
class ContractForm(forms.Form):
title = forms.CharField()
start_date = forms.DateField()
end_date = forms.DateField()
description = forms.CharField(widget=forms.Textarea)
client = forms.ModelChoiceField(queryset=Client.objects.all())
source
share