[英]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
this is the picture of my views.py这是我的views.py的图片
When I ran the code I saw an this error in the browser UnboundLocalError: local variable 'form' referenced before assignment当我运行代码时,我在浏览器中看到了这个错误 UnboundLocalError: local variable 'form' referenced before assignment
you only create form if your request is POST.仅当您的请求是 POST 时才创建表单。 so if you try to call your view with get method form variable is not created.因此,如果您尝试使用 get 方法调用视图,则不会创建表单变量。
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:如果用户将某些内容发布到您的注册视图,则会发生这种情况:他们在这种情况下是 go:
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.有效,因为它超出了 if 条件并且存在空表单。 but if a user tries to request the view with get method this code executes because condition checks for "POST":但是如果用户尝试使用 get 方法请求视图,则会执行此代码,因为条件检查“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.所以现在您可以看到您的代码无法理解form
的来源。
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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.