Prefilled form don't retreive excluded value in view

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 !

You have:

Where is MyId defined?

Also, you’ve excluded the id field - if you’re trying to save an existing instance, you must include the id field as a hidden field in the form for the POST action to know which instance to save. (Or, include the id field as a url parameter, which is the more-Djangoish style of handling this.)

Thank you for your help,
MyId was just to show that i’m inserting a data for the id field.
I understand how it works, i think i’ll try to insert the specific id in the value of the submit button to retreive it in the view.
But thank you again for your answer.

Side note: If you’re requesting help here with an error, you should be copy/pasting the exact code that you’re trying to run and not provide a representation of that code. Otherwise, we can’t provide accurate assistance with errors.

3 Likes