HenryM
HenryM

Reputation: 5793

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.

Upvotes: 1

Views: 2038

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

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()

Upvotes: 5

Related Questions