HenryM HenryM - 23 days ago 8
Python Question

Django Model Form not saving

I have a Django model form which when I use the following, isn't saving

if request.method == 'POST':
form = AbsenceForm(request.POST, instance=request.user)
if form.is_valid():
form.save()


forms.py

class DateInput(forms.DateInput):
input_type = 'date'

class AbsenceForm(forms.ModelForm):
class Meta:
model = NotWorking
exclude = ['user']
widgets = {
'date': DateInput()
}


Can you help please.

Answer

You're using instance wrong.

instance on a model form is supposed to be of the same class as the model you're referring to. It is used in UpdateViews to bind the form to an existing instance instead of creating a new instance up on save.

Example from the documentation:

# Create a form to edit an existing Article, but use
# POST data to populate the form.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()

In order to attach the user instance to the form you should set it on the form instead of providing it as an instance argument like detailed in this question.

if request.method == 'POST':
    form = AbsenceForm(request.POST)
    form
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
Comments