Python - Django - form 组件动态从数据库取 choices 数据

app01/models.py:

from django.db import models


class UserInfo(models.Model):
    username = models.CharField(max_length=16)
    password = models.CharField(max_length=16)
    mobile = models.CharField(max_length=11)


class City(models.Model):
    name = models.CharField(max_length=16, null=False, unique=True)

往 City 表中添加数据

 

这时候需要重启服务才能在页面上显示这些内容

也就是说每次数据库中的内容更新,都需要重启服务才能显示出来

可以通过重写父类中的 __init__ 方法来解决

views.py:

from django.shortcuts import render, HttpResponse
from app01 import models

from django import forms
from django.forms import widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class RegForm(forms.Form):
    username = forms.CharField(
        min_length=5,
        label="用户名",
        error_messages={
            "min_length": "用户名不能小于5位!",
            "required": "该字段不能为空"
        },
        widget=widgets.TextInput(attrs={"class": "form-control"})
    )

    password = forms.CharField(
        min_length=6,
        label="密码",
        error_messages={
            "min_length": "密码不能少于6位!",
            "required": "该字段不能为空"
        },
        widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True)
    )

    re_password = forms.CharField(
        min_length=6,
        label="确认密码",
        error_messages={
            "required": "该字段不能为空"
        },
        widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True)
    )

    mobile = forms.CharField(
        label="手机号",
        # 自定义正则匹配规则
        validators=[
            RegexValidator(r'^[0-9]+$', "手机号必须是数字"),  # 判断手机号是否为数字
            RegexValidator(r'^1[3-9][0-9]{9}$', "手机格式有误")  # 判断手机号是否为 1 和 3-9 开头的十一位数
        ],
        error_messages={
            "required": "该字段不能为空",
        },
        widget=widgets.TextInput(attrs={"class": "form-control"})
    )

    city = forms.ChoiceField(
        choices=models.City.objects.values_list("id", "name"),
        label="城市",
        initial=2,
        widget=widgets.Select()
    )

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

    # 判断用户名信息
    def clean_username(self):
        value = self.cleaned_data.get("username")
        if "admin" in value:
            raise ValidationError("用户名不能含有敏感信息")

    # 重写父类的 clean 方法
    def clean(self):
        password = self.cleaned_data.get("password")
        re_password = self.cleaned_data.get("re_password")
        if re_password != password:
            self.add_error("password", ValidationError("两次密码不一致"))
            self.add_error("re_password", ValidationError("两次密码不一致"))
            raise ValidationError("两次密码不一致")
        return self.cleaned_data


def reg2(request):
    form_obj = RegForm()  # GET 请求

    if request.method == "POST":
        form_obj = RegForm(request.POST)
        # 让 form 来帮我们进行校验
        if form_obj.is_valid():
            # 如果通过校验
            # 所有经过校验的数据都保存在 form_obj.cleaned_data
            print(form_obj.cleaned_data)
            models.UserInfo.objects.create(**form_obj.cleaned_data)
            return HttpResponse("注册成功")

    return render(request, "reg2.html", {"form_obj": form_obj})

运行结果:

 

posted @ 2019-09-10 20:51  Sch01aR#  阅读(1588)  评论(0编辑  收藏  举报