Home > OS >  "save() got an unexpected keyword argument 'commit'" error in functional view
"save() got an unexpected keyword argument 'commit'" error in functional view

Time:11-13

I got this error in my functional view: save() got an unexpected keyword argument 'commit' I'm try to save one object in database. 'debtors' is Many to Many field in models.py.

forms.py

class ExpenseForm(forms.ModelForm):
    class Meta:
        model = Expense
        fields = ('amount', 'text', 'debtors', 'date', 'time',)  
        
        widgets = {
            'date': AdminDateWidget(),
            'time': AdminTimeWidget(),
            'debtors': forms.CheckboxSelectMultiple(),
        }

views.py

def expenseformview(request, pk):
    if request.method == 'POST':
        form = Expense.objects.create(
            expenser = request.user,
            amount = request.POST.get('amount'),
            text = request.POST.get('text'),
            date = request.POST.get('date'),
            time = request.POST.get('time'),
        )
        form.debtors.add(request.POST.get('debtors'))  
                  
        formcoseshare = form.save(commit=False)
        formcoseshare.save()
        form.save_m2m()
        

        return redirect('expense_detail', pk=pk, expenseid=form.id)
    

    else:
        form = ExpenseForm()
        return render(request, 'financials/expense_form.html', {'form': form})

How can to solve this problem?

CodePudding user response:

Your form is not an ExpenseForm, it is a model object Expense, hence commit=False makes no sense, and neither does .save_m2m():

from django.contrib.auth.decorators import login_required


@login_required
def expenseformview(request, pk):
    if request.method == 'POST':
        form = ExpenseForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.expenser = request.user
            expense = form.save()
            return redirect('expense_detail', pk=pk, expenseid=expense.pk)
    else:
        form = ExpenseForm()
    return render(request, 'financials/expense_form.html', {'form': form})

It is however unclear to me what pk is doing here: you do not use it in any way.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

  • Related