會話保持及Form表單--Form表單


Form表單分為三種:Form表單都繼承自django.forms


1、簡單表單的使用(Form)

2、模型表單(ModelForm)

3、模型表單的自定義驗證

實例1:簡單表單的使用,博客用戶注冊表單

步驟

在項目目錄下創建forms.py,表單文件

from django import forms

class RegisterForm(forms.Form): username = forms.CharField(label='用戶名',max_length=20) #CharField 默認對應text類 password = forms.CharField(label='密碼',max_length=8, #字段名與input類中一一對應,會被渲染成input類型 min_length=6, #label屬性會被渲染成label標簽的內容 widget=forms.PasswordInput(attrs={'placehodler':'請輸入長度為6-8位的密碼'}), error_messages={ 'min_length':'密碼長度小於6位', 'max_length':'密碼長度大於8位' }) password_repeat = forms.CharField(label='請再次輸入密碼',widget=forms.PasswordInput()) email = forms.EmailField(required=False) #這個選項表示這個選項不是必填項,默認是必填選項 #自定義驗證密碼,重寫clean方法 def clean(self): cleaned_data = super().clean() #繼承父類的clean() 方法,使用驗證is_valid()方法會調用clean() password = cleaned_data.get('password') password_repeat = cleaned_data.get('password_repart') if password != password_repeat: msg = '密碼不一致!' self.add_error('password_repeat',msg)

在視圖view.py中添加:

def register(request):
    if request.method == 'GET':
        form = RegisterForm()


    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():   #調用is_valid()方法進行驗證時,需要調用clean()
            return  HttpResponse('注冊成功')
    return render(request, 'teacher/register.html', context={'form': form})

定義渲染頁面register.html代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
<form action="" method="post">  #填寫完畢后,提交出來
    {% csrf_token %}
    {{ form.as_p }}   #將forms表單中的屬性渲染出來
    <input type="submit" value="注冊">
</form>

</body>
</html>

在路由urls.py中添加:

    path('register/',views.register,name='register'),

實例二:模型表單

2.1、修改表單,自定義驗證身份證信息,以及使用標簽添加樣式,字段錯誤后顯示樣式等。

forms.py中添加如下代碼:

from django import forms
from teacher.models import StudentDetail,Student#模型表單
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student  #指定使用的模型
        exclude = ['is_deleted']  #排除列表中的字段
        # fields = ['name','age']   #添加


class StudentDetailForm(forms.ModelForm):
    class Meta:
        model = StudentDetail
        exclude = ['student']

    def clean_num(self):   #自定義驗證身份證信息
        data = self.cleaned_data.get('num')
        if not data[:-1].isdigit():
            raise forms.ValidationError('你輸入的號碼不正確')
        return  data

 

view.py中添加

from teacher.models import Student,Grade,StudentDetail,Course,Enroll
from teacher.forms import RegisterForm,StudentDetailForm,StudentForm

def new_edit(request,pk):
    section = '學生信息修改'
    student = Student.objects.get(pk =pk)
    form = StudentForm(instance=student)

    try:
        detail_form = StudentDetailForm(instance=student.studentdetail)
    except:
        #說明學生對象還沒有學生詳情
        student_detail = StudentDetail()
        student_detail.student=student
        student_detail.save()
        detail_form = StudentDetailForm(instance=student_detail)

    if request.method == 'POST':
        form = StudentForm(request.POST,instance=student)
        detail_form = StudentDetailForm(request.POST,instance=student.studentdetail)

        if form.is_valid() and detail_form.is_valid():
            form.save()
            detail_form.save()
            return redirect(reverse('teacher:students'))

    return  render(request,'teacher/student_edit_form.html',context={
        'section':section,
        'student':student,
        'form':form,
        'detail_form':detail_form
    })
student_edit_form.html代碼如下:
{% extends 'teacher/base.html' %}
{% block title %}添加學生{% endblock %}
{% load customer_tags %}
{% block section %} {{ section }}{% endblock %}
{% block content %}
    <form class="form-horizontal" method="post">
    {% csrf_token %}
        {% for field in form %}
{#           field.errors 字段的錯誤#}
            <div class="form-group {% if field.errors %}has-error{% endif %}">   #錯誤字段顯示紅色
            {% for error in field.errors %}                                 #渲染錯誤信息
                <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ error }}</label>
            {% endfor %}

    <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ field.label }}</label>   #渲染正式信息
    <div class="form-group">
    <label class="col-sm-2 control-label">{% add_class field 'form-control' %}</label>   #使用標簽添加樣式
        </div>
</div>
    {% endfor %}

    {% for field in detail_form %}
            <div class="form-group">
            {% for error in field.errors %}
                <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ error }}</label>
            {% endfor %}

    <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ field.label }}</label>
    <div class="form-group">
    <label class="col-sm-2 control-label">{% add_class field 'form-control' %}</label>
        </div>
</div>
    {% endfor %}
        <button type="submit" class="btn btn-primary">提交</button>
    </form>

{% endblock %}

使用標簽添加樣式代碼如下,在customer_tags.py中添加:

@register.simple_tag()
def add_class(field,class_str):
    return field.as_widget(attrs={'class':class_str})

在urls.py 中添加如下路由:

    path('newedit/<int:pk>/',views.new_edit,name='new_edit'),

 渲染效果如下:

2.2 使用模型表單重新定義“添加”學生

view.py中添加

def new_add(request):
    section = '添加學生'
    if request.method == 'GET':
        form = StudentForm()
        detail_form = StudentDetailForm()

    if request.method == 'POST':
            form = StudentForm(request.POST)
            detail_form = StudentDetailForm(request.POST)
            if form.is_valid() and detail_form.is_valid():
                student = form.save()
                #加上commit=False不會去真的保存到數據庫中
                #因為還要給它加上外鍵關聯對象
                student_detail = detail_form.save(commit=False)
                student_detail.student = student
                student_detail.save()

                return  redirect(reverse('teacher:students'))

    return render(request,'teacher/student_edit_form.html',
                  context={
                      'section':section,
                      'form':form,
                      'detail_form':detail_form
                  })

更新urls.py路由信息

path('student_add/',views.new_add,name='student_add'),

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com