2

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?

2
  • 2
    Your form is not a Form, it is a model object Expense, hence commit=False makes no sense, and neither does .save_m2m(). Commented Nov 12, 2022 at 20:12
  • Now, How can to solve problem? Commented Nov 12, 2022 at 20:15

1 Answer 1

2

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].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.