Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading