[Solved] Please I’m new to python and I’m trying to do a recipe app using Django. I encountered an error which is “UnboundLocalError: local variable form [closed]


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})

0

solved Please I’m new to python and I’m trying to do a recipe app using Django. I encountered an error which is “UnboundLocalError: local variable form [closed]