脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Django实现表单验证

Django实现表单验证

2021-04-01 00:20不凡De老五 Python

这篇文章主要为大家详细介绍了Django实现表单验证的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Django实现表单验证的具体代码,供大家参考,具体内容如下

models.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class Users(models.Model):
  nickname = models.CharField(max_length=16, null=False, blank=False, unique=True)
  email = models.EmailField(max_length=32, null=False, blank=False, unique=True)
  password = models.CharField(max_length=64, null=False, blank=False)
  head = models.ImageField(default="decault.png")
  age = models.CharField(max_length=3,blank=True,null=True)
  sex = models.CharField(max_length=2, blank=True, null=True)
  isactivate = models.BooleanField(default=False)
 
  def save(self):
    if not self.password.startswith('pbkdf2_'):
      self.password = make_password(self.password)
    super().save()

form.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from django import forms
from django.core.exceptions import ValidationError
 
from user.models import Users
 
#定义验证器
def nickname_validate(nickname):
  u = Users.objects.filter(nickname=nickname)
  if len(u):
    print(len(u))
    raise ValidationError('用户名已存在')
 
#定义表单
class RegisterForm(forms.Form):
  nickname = forms.CharField(validators=[nickname_validate],
                label='用户名',
                max_length=16,
                min_length=4,
                required=True,
                widget= forms.TextInput(),
                )
 
  password = forms.CharField(label='密码',
                max_length=64,
                min_length=6,
                required=True,
                widget=forms.PasswordInput())
 
  email = forms.EmailField(label='邮箱',
               max_length=32,
               required=True)
 
  age = forms.CharField(label='年龄',
             max_length=3,
             required=False)
 
  sex = forms.ChoiceField(label='性别',
              choices = ((0,'男'),(1,'女'),),
              required=False)

view.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from user.forms import RegisterForm
from user.models import Users
 
def register(request):
  if request.method == 'POST':
    form = RegisterForm(request.POST)
    if form.is_valid():
      u = Users()
      u.nickname = form.cleaned_data['nickname']
      u.email = form.cleaned_data['email']
      u.password = form.cleaned_data['password']
      u.age = form.cleaned_data['age']
      u.sex = form.cleaned_data['sex']
      u.save()
      return render(request,'user_info.html')
    else:
      return render(request, 'register.html',context={'form':form,'errors': form.errors})
  else:
    form = RegisterForm()
  return render(request,'register.html',context={'form':form})

register.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>注册</title>
</head>
<body>
  <form class="form" action="{% url 'user:register' %}" method="post">
    {% csrf_token %}
    <table>
      {{ form.as_p }}
    </table>
    <button type="submit" class="btn btn-primary btn-block">注册
    </button>
    <input type="hidden" name="next" value="{{ next }}"/>
  </form>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_38748717/article/details/79296467

延伸 · 阅读

精彩推荐