crazy-heng
天降大任于斯人也...

导航

 

利用ModelForm统一样式和个性化定制

 

统一样式我们用的比较多,直接上代码

class StarkModelForm(forms.ModelForm):
    """
    统一定制ModelForm类的样式
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

#编写一个类,在继承父类ModelForm的继承上,对每个字段循环,给他们统一添加一个class, 这样在bootstrap下可以统一样式

class AddModelForm(StarkModelForm):
class Meta:
model = 数据库中的类
fields = '__all__' # 也可以自定义选择显示字段
 

 

不同的字段定制不同的样式

class StarkModelForm(forms.ModelForm):
    """
    统一定制ModelForm类的样式
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

#编写一个类,在继承父类ModelForm的继承上,对每个字段循环,给他们统一添加一个class, 这样在bootstrap下可以统一样式


class AddModelForm(StarkModelForm):

  class Meta:

  model = models.UserInfo
    fields = ['name', 'password', 're_pwd', 'nickname', 'gender', 'phone', 'email', 'depart', 'role']
widgets = {
'password': forms.PasswordInput
}
# widgets 设置插件, 可以根据不同的字段设置各种参数
      

 

在ModelForm中添加非model中的字段

当我们需要额外添加一个不属于model的字段时就需要注意他的定制样式和model中的字段不一样,比如添加一个用户model中没有确认密码,但是我们一般都需要确认密码这个选项时,就需要单独定制他的样式


class StarkModelForm(forms.ModelForm):
    """
    统一定制ModelForm类的样式
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

class
UserInfoAddModelForm(StarkModelForm): """ 添加用户的ModelForm """ re_pwd = forms.CharField(label='确认密码', widget=forms.PasswordInput) #单独定制widget class Meta: model = models.UserInfo fields = ['name', 'password', 're_pwd', 'nickname', 'gender', 'phone', 'email', 'depart', 'role'] widgets = { 'password': forms.PasswordInput, }

 

 

验证密码和确认密码是否一致、用户名是否存在数据库中

class StarkModelForm(forms.ModelForm):
    """
    统一定制ModelForm类的样式
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'





class UserInfoAddModelForm(StarkModelForm):
    """
    添加用户的ModelForm
    """
    re_pwd = forms.CharField(label='确认密码', widget=forms.PasswordInput)

    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 're_pwd', 'nickname', 'gender', 'phone', 'email', 'depart', 'role']
        widgets = {
            'password': forms.PasswordInput,
        }

    def clean_re_pwd(self):
        """
        验证密码是否一致
        :return:
        """
        password = self.cleaned_data.get('password')
        re_pwd = self.cleaned_data.get('re_pwd')
        if password != re_pwd:
            raise ValidationError('两次密码不一致')
        return re_pwd

    def clean_name(self):
        """
        验证用户是否注册
        :return:
        """
        username = self.cleaned_data['name']
        r_username = models.UserInfo.objects.filter(name=username)
        if r_username:
            raise ValidationError('用户名已存在')
        return username

   

 

 

利用全局钩子,在局部验证完成后对密码进行md5后再存入数据库


from web.utils.md5 import gen_md5


class
UserInfoAddModelForm(StarkModelForm): """ 添加用户的ModelForm """ re_pwd = forms.CharField(label='确认密码', widget=forms.PasswordInput) class Meta: model = models.UserInfo fields = ['name', 'password', 're_pwd', 'nickname', 'gender', 'phone', 'email', 'depart', 'role'] widgets = { 'password': forms.PasswordInput, } def clean(self): """ 全局钩子,将密码加密后存入数据库 :return: """ password = self.cleaned_data.get('password') self.cleaned_data['password'] = gen_md5(password) return self.cleaned_data

 

md5.py
import hashlib


def gen_md5(origin):
    """
    md5加密
    :param origin:
    :return:
    """
    ha = hashlib.md5()
    ha.update(origin.encode('utf-8'))
    return ha.hexdigest()

 

posted on 2019-06-18 18:06  killer-147  阅读(696)  评论(0编辑  收藏  举报