Python - Django - form 組件動態從數據庫取 choices 數據

app01/models.py:html

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 表中添加數據python

 

這時候須要重啓服務才能在頁面上顯示這些內容數據庫

也就是說每次數據庫中的內容更新,都須要重啓服務才能顯示出來django

能夠經過重寫父類中的 __init__ 方法來解決app

views.py:ui

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})

運行結果:code

相關文章
相關標籤/搜索