Django – Form和ModelForm组件

表单的很多字段信息, 和models.py文件里的模型是一致的,为了避免重复代码,以及提高效率, 可以使用ModelForm,将模型和表单进行绑定。

1. Form

1.1 views.py

//创建业务类MyForm, 继承django中Form类
class MyForm(Form):  
    // Form类会在html中渲染出原始表单
    user = forms.CharField(widget=forms.Input)
    pwd = form.CharFiled(widget=forms.Input)
    email = form.CharFiled(widget=forms.Input)
    account = form.CharFiled(widget=forms.Input)
    create_time = form.CharFiled(widget=forms.Input)
    depart = form.CharFiled(widget=forms.Input)
    gender = form.CharFiled(widget=forms.Input)


def user_add(request):
    if request.method == "GET":
        form = MyForm()
        return render(request, 'user_add.html',{"form":form})

 

1.2 user_add.html (Form)

<form method="post">
    {% for field in form%}
    	{{ field }}
    {% endfor %}
    <!-- <input type="text"  placeholder="姓名" name="user" /> -->
</form>

或者

<form method="post">
    {{ form.user }}
    {{ form.pwd }}
    {{ form.email }}
    <!-- <input type="text"  placeholder="姓名" name="user" /> -->
</form>

 

 

2. ModelForm

 

2.1 models.py 

class UserInfo(models.Model):
    """ 员工表 """
    name = models.CharField(verbose_name="姓名", max_length=16)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄")
    account = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    create_time = models.DateTimeField(verbose_name="入职时间")
    depart = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE)
    gender_choices = (
        (1, "男"),
        (2, "女"),
    )
    gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)

 

 

2.2 views.py 快速建立表单

class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=2, label="用户名")
    password = forms.CharField(label="密码")
    class Meta:
        model = UserInfo
        fields = ["name","password","age","xx"]


def user_add(request):
    if request.method == "GET":
        form = MyForm()
        return render(request, 'user_add.html',{"form":form})

2.3 views.py 给表单添加样式

 

class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=2, label="用户名")
    password = forms.CharField(label="密码")
    # create_time = forms.DateTimeField()
    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart']
        
        # 方法1: 为前端元素添加类属性, 使其获得样式. 

        # widgets = {
        #     "name":forms.TextInput(attrs={"class":"form-control"})
        # }

        # 方法2: 为前端元素添加类属性, 使其获得样式. 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  #super() 函数是用于调用父类(超类)的一个方法。
        for name, field in self.fields.items():
            field.widget.attrs = {"class":"form-control", "placeholder":field.label}

 

 

2.4 user_add.html (ModelForm)

<form method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
        <div class="form-group">
            <label>{{ field.label }}</label>
            {{ field }}
            <span style="color: red">{{ field.errors.0 }}</span>
        </div>
    {% endfor %}

    <button type="submit" class="btn btn-primary">提交</button>

</form>

 

 

 

本站文章除单独注明外均为原创,本文链接https://bowmanjin.com/299,未经允许请勿转载。

0

评论0

请先

没有账号? 注册  忘记密码?