我正在使用Django框架创建一个注册表单,我想在用户输入错误的确认密码或已经采取的电子邮件时显示一些错误消息。我写的代码,它似乎是工作,但我似乎不能得到的消息显示在屏幕上重定向回注册页,如果有一个错误的形式。我已经在views.py页面上导入了消息(从django。我认为我的setting.py配置正确:setting.py
这是我的views.py代码:
def register(request):
if request.method == "GET":
register_form = RegisterForm()
return render(request, "main/register.html", {
'form': register_form
})
else:
register_form = RegisterForm(request.POST)
if register_form.is_valid():
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirm_password = request.POST['confirm_password']
if password == confirm_password:
if User.objects.filter(email=email).exists():
messages.info(request, 'Email or user name Already taking')
return redirect('register')
elif User.objects.filter(username=username).exists():
messages.info(request, 'username is taken')
return redirect('register')
else:
User.objects.get_or_create(username=username,
first_name=first_name, last_name=last_name, email=email,
password=password)
return redirect('main/login.html')
else:
messages.error(request, 'Password Not Match')
return redirect('register')
#return redirect ('/')
else:
return render(request, 'main/login.html')
这是我的register。html表单:
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend>Enter details</legend>
<ul>
{{ form.as_table }}
<button type="submit" class="mybutton _f-purple" value="submit">Register</button>
</ul>
</fieldset>
</form>
我想这就是你需要的。
{% if messages %}
<div class="mgs-area">
<div class="mgs-item">
{% for message in messages %}
<span {% if message.tags %} class="nav_item message-{{ message.tags }} " {% endif %}> {{ message }} </span>
{% endfor %}
</div>
</div>
{% endif %}
你可以给成功或错误消息设置不同的样式。
class="nav_item message-{{消息。标签}}