当我按下“提交”按钮时,我想创建一个像“注册”之类的用户或注册,但出现此错误:
/ signup /
处的UnboundLocalError我要注册用户:
local variable 'usercustom' referenced before assignment
这是我的Views.py
def signup(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST or None)
custom_form = UserCustom(request.POST or None)
if user_form.is_valid() and custom_form.is_valid():
user = user_form.save(commit=False)
user.save()
custom = custom_form.save(commit=False)
custom.user = user
custom.save()
registered = True
else:
print(user_form.errors,custom_form.errors)
else:
user_form = UserForm()
usercustom = UserCustom()
return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})
这是我的Form.html
{% extends "base.html" %}
{% block body_block %}
<div class="content-section">
{% if registerd %}
<h1>Thank Your For registering!</h1>
{% else %}
<h1>Register Here</h1>
<h3>Fill out the form</h3>
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ usercustom.as_p }}
<input type="submit" value="Register!" class="btn btn-danger">
</form>
{% endif %}
</div>
{% endblock %}
答案 0 :(得分:0)
这是因为尝试发送POST请求时未声明usercustom。您需要将custom_form
变量重命名为usercustom
。我为您简化了代码。
def signup(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST or None)
usercustom = UserCustom(request.POST or None)
if user_form.is_valid() and usercustom.is_valid():
user = user_form.save(commit=False)
user.save()
custom = usercustom.save(commit=False)
custom.user = user
custom.save()
registered = True
else:
print(user_form.errors, usercustom.errors)
else:
user_form = UserForm()
usercustom = UserCustom()
return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})