Home > front end >  Please I'm new to python and I'm trying to do a recipe app using Django. I encountered an
Please I'm new to python and I'm trying to do a recipe app using Django. I encountered an

Time:09-02

this is the picture of my views.py

When I ran the code I saw an this error in the browser UnboundLocalError: local variable 'form' referenced before assignment

CodePudding user response:

you only create form if your request is POST. so if you try to call your view with get method form variable is not created.


this is your code I'm gonna walk you through it.

def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request,f"{username}, your account has been created!")
            return redirect('recipes-home')
        else:
            form = UserCreationForm()
    return render(request,'users/Register.html',{'form',form})

if a user post something to your register view this happens: they go in this condition:

form = UserCreationForm(request.POST)
if form.is_valid():
    username = form.cleaned_data.get('username')
    messages.success(request,f"{username}, your account has been created!")
    return redirect('recipes-home')
else:
    form = UserCreationForm()

if data is valid they get redirected. else an empty form is created and then this line:

return render(request,'users/Register.html',{'form',form})

works because it's out of if condition and an empty form exists. but if a user tries to request the view with get method this code executes because condition checks for "POST":

def register(request):
    return render(request,'users/Register.html',{'form',form})

so now you can see that your code can't understand where did the form came from.

you can use this to make your code work.

def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request,f"{username}, your account has been created!")
            return redirect('recipes-home')
        else:
            form = UserCreationForm()
    if request.method == "GET":
        form = UserCreationForm()
    return render(request,'users/Register.html',{'form',form})
  • Related