Django 常用的Form表单

Django最强大的部分之一是自动管理界面。它从模型中读取元数据,以提供一个快速的,以模型为中心的界面,受信任的用户可以在其中管理您网站上的内容。管理员的建议用法仅限于组织的内部管理工具。它并非旨在构建您的整个前端。

Django Form

普通Form表单的提交





    
    Title


    

账号:{{ error.username }}

密码:{{ error.password }}

# name: views.py
from django.shortcuts import render,HttpResponse

def index(request):
    if request.method == "GET":
        return render(request,"index.html")
    else:
        username = request.POST.get("username")
        password = request.POST.get("password")
        error = {"username":"","password":""}
        if len(username) > 10:
            error["username"]="用户名不能大于10"
        if len(password) < 5:
            error["password"] = "密码不能小于5"
        return render(request,"index.html",{"error":error})

Form实现登录表单





    
    Title


    

账号: {{ form.username }} {{ form.username.errors.0 }}

密码: {{ form.password }} {{ form.errors.password }}

重复: {{ form.RepeatPass }} {{ form.errors.RepeatPass }}

# name:views.py
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets
from django.core.exceptions import ValidationError

class LoginForm(Form):
    username = fields.CharField(
        required = True,
        max_length = 10,
        error_messages={"required":"该字段不能为空"},
        widget=widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})
    )
    password = fields.CharField(
        required = True,
        max_length=10,
        error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
        widget=widgets.PasswordInput(attrs={"placeholder":"请输入密码","class":"form-control"})
    )
    RepeatPass = fields.CharField(
        required=True,
        max_length=10,
        error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
        widget=widgets.PasswordInput(attrs={"placeholder":"重复输入密码","class":"form-control"})
    )

    # 自定义方法(局部钩子)密码必须包含字母和数字
    def clean_password(self):
        if self.cleaned_data.get("password").isdigit() or self.cleaned_data.get("password").isalpha():
            raise ValidationError("密码必须包含数字和字母")
        else:
            return self.cleaned_data["password"]
    # 自定义方法(全局钩子, 检验两个字段),检验两次密码是否一致
    def clean_RepeatPass(self):
        if self.cleaned_data.get("password") != self.cleaned_data.get("RepeatPass"):
            raise ValidationError("两次输入密码不正确")
        else:
            return self.cleaned_data

def index(request):
    if request.method =="GET":
        form = LoginForm()
        return render(request, "index.html", {"form": form})
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            # username = form.data['username']
            data = form.cleaned_data
            username = data.get("username")
            password = data.get("password")
            print(username,password)
            return render(request, "index.html", {"form": form})
    return render(request, "index.html", {"form": form})

Form实现用户注册





    
    Title


    

{{ form.username.label }} {{ form.username }}

{{ form.password.label }} {{ form.password }}

{{ form.mobile.label }} {{ form.mobile }}

{{ form.email.label }} {{ form.email }}

{{ form.text }}

# name: models.py
from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=64)
    password = models.CharField(max_length=32)
    mobile = models.CharField(max_length=32)
    email = models.EmailField(max_length=64)
    text = models.CharField(max_length=128)
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.forms import Form,fields,widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

class UserForm(Form):
    username = fields.CharField(
        label = "账号: ",          # 给表单加一个标签
        required = True,           # 不允许字段为空值
        min_length=4,              # 设置最小长度
        max_length = 10,           # 设置最大长度
        validators=[ RegexValidator(r'^[0-9a-zA-Z]+$',"用户账号只能使用,0-9a-z") ],
        error_messages={"required":"该字段不能为空","invalid":"无效的用户名",
                        "min_length":"最小长度为5","max_length":"最大长度为10"},
        widget=widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})
    )
    password = fields.CharField(
        label = "密码: ",
        required = True,
        min_length=5,
        max_length=10,
        error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
        widget=widgets.PasswordInput(attrs={"placeholder":"请输入密码","class":"form-control"})
    )
    mobile = fields.CharField(
        label = "手机: ",
        required=True,
        validators=[RegexValidator('[0-9]', "手机号必须是数字")],
        error_messages={"required":"该字段不能为空"},
        widget=widgets.TextInput(attrs={"placeholder": "手机号","class": "form-control"})
    )
    email = fields.EmailField(
        label="邮箱: ",
        required=True,
        error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
        widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"})
    )
    text = fields.CharField(
        required=True,
        widget=widgets.Textarea(attrs={"placeholder": "畅言,欢迎留言...", "class": "form-control",
                                       "style":"margin: 0px; width: 203px; height: 98px;"})
    )

def index(request):
    if request.method =="GET":
        form = UserForm()
        return render(request, "index.html", {"form": form})
    else:
        form = UserForm(request.POST)
        if form.is_valid():
            # username = form.data['username']
            data = form.cleaned_data
            username = data.get("username")

            is_exits = models.User.objects.filter(username="admin").count()
            if is_exits != 0:
                return HttpResponse("您注册的用户已存在")
            else:
                models.User.objects.create(**data)
                return HttpResponse("恭喜您的账号注册完成了")
        else:
            return render(request, "index.html", {"form": form.errors})
    return render(request, "index.html", {"form": form})

其他常用Form表单





    
    Title


    
{% for field in form %}

{{ field.label_tag }} {{ field }} {{ field.errors.0 }}

{% endfor %}
# name: views.py
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets

class MyForm(Form):
    hobby = fields.ChoiceField(
        label="单选框:",
        required=True,
        initial=1,                # 默认选择1号
        choices=( (1,"篮球"),(2,"足球"),(3,"乒乓球"),(4,"滚球")),
        widget=widgets.RadioSelect()
    )
    select = fields.ChoiceField(
        label="单选框(默认):",
        required=True,
        initial=1,
        choices=( (1,"篮球"),(2,"足球"),(3,"乒乓球"),(4,"滚球")),
        widget=widgets.Select()
    )
    multiple = fields.MultipleChoiceField(
        label="复选框",
        choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),
        initial=[2, 4],
        widget=widgets.SelectMultiple()
    )
    checkbox = fields.ChoiceField(
        label="单项复选框",
        initial="checked",  # 默认为勾选
        widget=widgets.CheckboxInput()
    )
    multselect = fields.MultipleChoiceField(
        label="多项复选框",
        choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),
        initial=[1, 3],
        widget=widgets.CheckboxSelectMultiple()
    )
    data = fields.DateField(
        label="选择日期",
        widget = widgets.DateInput(attrs={"type":"date"})
    )
    files = fields.FilePathField(path="./MyProject",
                                allow_folders=True,recursive=True)
    ip = fields.GenericIPAddressField(protocol="both",unpack_ipv4=False)
def index(request):
    if request.method=="GET":
        form = MyForm()
        return render(request,"index.html",{"form":form})
    else:
        form = MyForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            print(data.get("hobby"))
    return HttpResponse("hello lyshark")

重写父类方法 通过form表单重写init方法,实现数据库动态添加,前端动态显示,以两个选择框为例

# name: models.py
from django.db import models

class DBHost(models.Model):
    id = models.AutoField(primary_key=True)
    host = models.CharField(max_length=32)
    title = models.CharField(max_length=32)

# name:index.html
{{ form.title }}
{{ form.host }}
# name:views.py
from django.shortcuts import render
from django.forms import Form,fields,widgets
from MyWeb import models

class DBHost(Form):
    title = fields.IntegerField(widget=widgets.Select(choices=[]))
    host = fields.IntegerField(widget=widgets.SelectMultiple(choices=[]))

    # 重写父类的 __init__ 方法
    def __init__(self,*args,**kwargs):
        super(DBHost, self).__init__(*args,**kwargs)
        self.fields['title'].widget.choices = models.DBHost.objects.all().values_list("id","title")
        self.fields['host'].widget.choices = models.DBHost.objects.all().values_list("id", "host")

def index(request):
    form = DBHost()
    return render(request,"index.html",{"form":form})

给Form表单返回数据 Form表单可以返回默认数据,我们可以通过编号查询到指定数据的默认参数,并返回到编辑框中.

# name:views.py
from django.shortcuts import render
from django.forms import Form,fields,widgets
from MyWeb import models

class MyForm(Form):
    host = fields.CharField(required=True,widget=widgets.TextInput())
    title = fields.CharField(required=True, widget=widgets.TextInput())

def index(request):
    nid = request.GET.get("id")   # 通过ID获取到记录
    qset = models.DBHost.objects.filter(id=nid).values("host","title")
    dic = qset[0]  # 转为字典

    form = MyForm(dic) # 传递到前端编辑框中
    return render(request,"index.html",{"form":form})

你可能感兴趣的