python - UnboundLocalError at /vnos/ -


i'm building test aplication insert data database , keep on getting error "local variable 'form' referenced before assignment". read few articles , not understand how should approach problem in case method not post.

all i'm trying acchieve test application go specified page, insert numbers in fields , submit them. after want check db if got submitted correctly.

views.py

def cost(request): if request.method == 'post':     form = costform(request.post)     if form.is_valid():         amount = request.post.get('amount', '')         cost = request.post.get('cost', '')         cost_obj = cost(amount = amount, cost = cost)         cost_obj.save()          return httpresponseredirect('/vnos/')     else:         form = costform()  return render(request, "cost.html", {'form': form}) 

models.py

class cost(models.model): cost = models.floatfield() amount = models.floatfield() 

forms.py

class costform(forms.form): date = forms.datefield() amount = forms.floatfield()  class meta:     model = cost     fields = ['cost', 'amount'] 

your else statement indented far. move 1 level.

two other points: should getting data form after validation, not direct post:

    amount = form.cleaned_data['amount']     cost = form.cleaned_data['cost'] 

and secondly, make simpler using modelform.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -