我尝试在Django中创建一个简单的注册页面,并检查所有字段的验证。我尝试检查电子邮件字段的格式验证,但我找不到任何源代码来做这件事。你能帮助我吗?
这里是www.example.comview.py:
from django.shortcuts import render
from django.http import HttpResponse, request
from django.db import connection
from django.contrib.auth.decorators import login_required
import pyodbc
def newUser(request):
form = NewUserFrom(request.POST or None)
if not form.is_valid():
context = {'frmNewUser':form}
return render(request,'login/newuser.html', context)
return render(request, "login/welcome.html")
这里是www.example.comforms.py:
from ctypes import alignment
from email import message
from urllib import request
from django import forms
class NewUserFrom(forms.Form):
error_css_class = 'error'
username = forms.CharField(max_length=50, widget=forms.TextInput, label="Username")
password = forms.CharField(widget=forms.PasswordInput, label="Password")
confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput)
name = forms.CharField(max_length=50, widget=forms.TextInput, label="Name")
email = forms.EmailField(max_length=50, widget=forms.EmailInput, label="Email")
def clean_password(self):
cleaned_data = super().clean()
pwd = cleaned_data.get('password')
cof_pwd = cleaned_data.get('confirm_password')
# if pwd and cof_pwd:
if pwd != cof_pwd:
raise forms.ValidationError('Password is not match.')
return cleaned_data
def clean(self):
cleaned_data = super(NewUserFrom,self).clean()
email = cleaned_data.get('email')
if email.strip() == "".strip():
# self.add_error('email','Email is reqiered.')
raise forms.ValidationError('Email is reqiered.')
else:
fistPart, secPart = str(email).split('@')
raise forms.ValidationError('Email error.')
下面是新用户的. html:
{% block content %}
<form method="POST">
{% csrf_token %}
<table>
{{frmNewUser.as_table}}
{% for field in frmNewUser.fields %}
{% if field.errors %}
{% for error in field.errors %}
<p style="color: red;">{{error}}</p>
{% endfor %}
{% endif %}
{% endfor %}
</table>
<input type="submit" name="Save" value="Save" colspan=2>
</form>
{% endblock content %}
2条答案
按热度按时间yqkkidmi1#
使用Django自带的内置电子邮件验证器总是更安全,建议使用。
您在声明email时没有输入blank=True和null=True,所以Django会一直确保这个字段不为空。Django也会确保用户只输入有效的email地址。事实上,您不需要做其他任何事情。
参考:https://docs.djangoproject.com/en/3.2/ref/forms/fields/#django.forms.Field.clean
mqxuamgl2#
如果您想修改Django表单中的电子邮件地址
类忘记密码电子邮件表单(表单。表单):