znawca
znawca

Reputation: 279

view "add product" - does not work

i created a model which contains name and price. I made a view that will help me with adding products on my site:

def new_expense(request):
    if request.method == "EXPENSE":
        form = ExpenseForm(request.EXPENSE)
        if form.is_valid():
            expense = form.save(commit=False)
            expense.save()
            return redirect('homebudget.views.expense_detail', pk=expense.pk)
    else:
        form = ExpenseForm()
    return render(request, 'homebudget/edit_expense.html', {'form': form})

Now i have something like that: https://i.sstatic.net/3RbQr.png but when i click save there's nothing happening! What must i change in view?

forms.py:

class ExpenseForm(forms.ModelForm):

class Meta:
    model = Expense
    fields = ('name', 'price',)

models.py:

class Expense(models.Model):
    name = models.CharField(max_length=40)
    price = models.FloatField("price")

Upvotes: 1

Views: 40

Answers (1)

aumo
aumo

Reputation: 5554

request.method cannot be equal to EXPENSE, it may only be a HTTP method name. In the same way, request.EXPENSE is not defined. I don't know how the request is done but what you probably want to test is:

if request.method == 'POST':
    form = ExpenseForm(request.POST)

Note:

expense = form.save(commit=False)
expense.save()

and

expense = form.save()

are equivalent.

Upvotes: 3

Related Questions