我正在使用django为新用户创建注册表单。如果用户输入无效,我希望页面重新加载无效的表单和自定义错误消息。所以基本上,我试图找到一种方法来返回无效的表单以及在else语句上重新加载页面。
<div id="signupboxelementscontainer">
<form action="" method="post" name="signupform">
{% csrf_token%}
<div id="namerow" class="row">
<input name="firstname"id="firstname" class="formelements" placeholder="First name" type="text">
<input name="lastname" id="lastname" class="formelements" placeholder="Last name" type="text">
</div>
<input name="email" id="email" class="formelements" placeholder="Email address" type="email">
<br>
<input name="storename" id="storename" class="formelements" placeholder="Your store name" type="text">
<input name="password" id="password" class="formelements" placeholder="Password" type="password">
<br>
<input name="passwordagain" id="passwordagain" class="formelements" placeholder="Retype password" type="password">
<br>
<div class="row">
</div>
<button id="submitbutton" type="submit"> Submit</button>
</div>
<p>Already have an account? <a href="{% url 'login'%}">Sign in</a> </p>
<p id="error">{{ error_message }}</p>
</div>
def signup(request):
if request.method == "POST":
signupform = signupform(request.POST)
first_name = request.POST.get("firstname")
last_name = request.POST.get("lastname")
email = request.POST.get("email")
storename = request.POST.get("storename")
password = request.POST.get("password")
passwordagain = request.POST.get("passwordagain")
if password == passwordagain:
user = User.objects.create_user(first_name=first_name,last_name=last_name,email = email, password = password, username=storename)
else:
error_message = "Your passwords do not match"
return render(request,'main/signup.html', {"error_message": error_message,"signupform": signupform,})
return render(request, "main/signup.html",)
答案 0 :(得分:1)
尝试使用Django的表单库。请参阅https://docs.djangoproject.com/en/2.1/topics/forms/
上的示例这将完成您想要的并使代码更简单。其他任何事情都会更加复杂。