python中使用ModelForm

models.py

class Department(models.Model):
    """部门表"""
    title = models.CharField(max_length=32, verbose_name='部门表')

    def __str__(self):
        return self.title

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

    # 级联删除
    depart = models.ForeignKey(to='Department', to_field='id', on_delete=models.CASCADE, verbose_name='部门')

views.Py

from django import forms


class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=3, label='用户名')
    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        for name, field in self.fields.items():
            #html元素添加属性
            field.widget.attrs = {'class': 'form-control'}


def user_model_form_add(request):
    """modelForm 添加用户"""
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {'form': form})

    # 用户POST提交数据,数据校验
    form = UserModelForm(data=request.POST)
    # 验证数据
    if form.is_valid():
        # 保存到数据库
        form.save()
        return redirect('/user/list/')
        # print(form.cleaned_data)

    # 校验失败
    print(form.errors)
    return render(request, 'user_model_form_add.html', {'form': form})

你可能感兴趣的:(python)