简体   繁体   中英

local variable 'form' referenced before assignment in python

this code always show me error local variable 'form' referenced before assignment

def home(request):

    if request.method=='POST':
        form = ListForm(request.POST or None) 

    if form.is_valid(): 
        form.save() 
        all_items = list.object.all 
        messages.success(request ,('Item Has Been Added To List !')) 
        return render(request ,'home.html', {'all_items': all_items}) 
    else : 
        all_items = list.object.all 
        return render(request, 'home.html', {'all_items': all_items})

The variable form is defined only if the the condition request.method == 'POST' fulfills otherwise you won't have the from variable in the function scope. The code should look like this in order to resolve your issue:

if request.method=='POST':
   form = ListForm(request.POST)
else:
   form = ListForm(None)
def home(request):
    all_items = list.object.all()
    if request.method=='POST':
        form = ListForm(request.POST or None) 
        if form.is_valid(): 
            form.save() 
            messages.success(request ,('Item Has Been Added To List !')) 
            return redirect('home.html') 
    else :
        form = ListForm()
    return render(request, 'home.html', {'all_items': all_items, 'form': form})

in case of a get request the form again will be thrown to the user

you can do this as the statement will circuit-break on the left side of the and

if 'form' in locals() and form.is_valid(): 
    ... do something
def home(request):
    if request.method == 'POST':
      form = ListForm(request.POST or None)
      form = ListForm(request.POST)  
        if form.is_valid():
            form.save()
            all_items = list.objects.all
            messages.success(request, ('Item has been added to do list!'))
            return render(request, "home.html", {'all_itmes':all_items})
        else:
            print(form.errors)
            return HttpResponse(form.errors)
    else:
        all_items = list.objects.all
        return render(request, "home.html", {'all_itmes':all_items})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM