Good morning,
I’m blocked with the use of Django forms.
I have the form below, with two fields and one excluded
forms.py
[...]
class MyForm(forms.ModelForm) :
class Meta :
model = MyModel
fields = (
'date',
'commentary'
)
exclude = ['userID']
widgets = {
'date':DateInput(attrs={'class': 'form-control'}),
'commentary': forms.Textarea(attrs= {'class': 'form-control'})
}
[...]
Which I then use in my view to generate a pre-filled form before my page load.
view.py
[...]
def mainPage(request):
#when clicking on the input button only...
if request.method == "POST" and "SubmitButton" in request.POST:
validForm = MyForm(request.POST)
if validForm.is_valid():
saveForm = validForm.save(commit=False)
saveForm.save()
#at the first load only...
else:
mainPage.form = MyForm(instance=MyModel('id'=MyId))
#so here i have a pre-filled form with the id and showing free fields for date and commentary
return render(request, 'myUrl/mainPage.html', { 'preffilledForm' : mainPage.form})
and the html is
MyPage.html
[...]
<form method="POST">{% csrf_token %}
{{ prefilledForm.as_p }}
<button type='Submit' name='SubmitButton'>Submit</button>
</form>
[...]
So i thought that when i click on the submit button after completing the date and commentary of the form, i should retrieve the complete object in the view by doing validForm = MyForm(request.POST)
.
With the id i already entered in the form and with the new date and commentary. But i get this error message
NOT NULL constraint failed: MyModel.id
What do you think I’m doing wrong?
Thanks in advance !