关于python:python中使用ModelForm

54次阅读

共计 1438 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0