1. 程式人生 > >Django之Form元件補充

Django之Form元件補充

一、定義的規則

class TeacherForm(Form):  #必須繼承Form
    # 建立欄位,本質上是正則表示式
    username = fields.CharField(
        required=True,     #必填欄位
        error_messages={"required":"使用者名稱不能為空!!"},  #顯示中文錯誤提示
        widget=widgets.TextInput(attrs={"placeholder":"使用者名稱","class":"form-control"}),  #自動生成input框
        label="
姓名", label_suffix=":" ) password = fields.CharField(required=True, error_messages={'required': '密碼不能為空'}, widget=widgets.PasswordInput(attrs={'placeholder': '密碼', 'class': 'form-control'}), label="密碼", label_suffix
=":" ) # 不能為空 email = fields.EmailField( required=True, error_messages={"required":"郵箱不能為空!!","invalid":"無效的郵箱"}, widget=widgets.EmailInput(attrs={"placeholder": "郵箱", "class": "form-control"}), # 自動生成input框 label = "郵箱", label_suffix = ":" )
#不能為空且郵箱格式要一致

頁面上渲染

用第二種方式需要加上下面的這個:

 二、下拉框的規則

 

三、判斷使用者民是不存在,存在就不添加了

需要匯入:

from django.core.exceptions import ValidationError

四、initial  修改時用到

 

五、自定義配置

1、在settings中:

2、匯入settings

from django.conf import settings

 3、使用

 六、多對多修改兩種方式(用Form)

def editteacher(request,nid):
    obj = models.UserInfo.objects.filter(id=nid, ut_id=1).first()
    # print(obj.username)
    if not obj:
        return redirect("/teacherindex/")
    if request.method=="GET":
        print([obj.id for obj in obj.teacher_classes.all()])  #[2]  拿到select框的id是為了要做預設顯示的
        form = TeacherForm(initial={"username":obj.username,"password":obj.password,"email":obj.email,"teacher_classes":[obj.id for obj in obj.teacher_classes.all()]}) #就讓顯示一個input框,並且帶有原來哪一行的內容
        return render(request, "editteacher.html", {"form":form})
    else:
        form = TeacherForm(data=request.POST)
        if form.is_valid():#開始校驗,注意這要加括號
            cls_list = form.cleaned_data.pop("teacher_classes")
            print(cls_list)
            models.UserInfo.objects.filter(id=nid).update(**form.cleaned_data)
            obj.teacher_classes.set(cls_list)   #更新第三張表
            return redirect("/teacherindex/")
        else:
            return render(request, "editteacher.html", {"form":form})

七、多對多新增(用Form)

def addteacher(request):
    if request.method=="GET":
        form = TeacherForm()  #只是讓顯示一個input框
        return render(request, "addteacher.html", {"form":form})
    else:
        form = TeacherForm(data=request.POST)
        # print(form)  #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
        if form.is_valid():# 開始驗證
            # print('執行成功',form.cleaned_data)          # 所有匹配成功,字典
            # # {'username': 'ghf', 'password': '435', 'email': '[email protected]', 'teacher_classes': ['4']}
            cls_list = form.cleaned_data.pop("teacher_classes")
            print("============id",cls_list)
            form.cleaned_data['ut_id'] = 1
            #建立新老師的物件
            teacher_obj = models.UserInfo.objects.create(**form.cleaned_data)
            #建立新老師和班級的關係
            teacher_obj.teacher_classes.add(*cls_list)  #以前新增的是物件,現在也可以吧id新增進去
            return redirect("/teacherindex/")
        else:
            # print("=====?",form.errors,type(form.errors))#返回失敗的結果
            # print(form.errors["username"][0])   #拿到返回失敗的結果,渲染到頁面
            return render(request, "addteacher.html", {"form":form})