美文网首页
ModelForm使用方法

ModelForm使用方法

作者: 戴维得 | 来源:发表于2017-10-08 01:15 被阅读0次

    首先查看model里面定义的类

    class UserInfo(models.Model):
        """
        用户表
        """
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=64)
        nickname = models.CharField(max_length=32)
        email = models.EmailField()
    
        roles = models.ManyToManyField('Role')
    
        def __str__(self):
            return self.nickname
    

    然后在view里面这样写,表示创建ModelForm类

    from django.forms import ModelForm
    from django.forms import widgets as wid
    from django.forms import fields as fld
    class UserModelForm(ModelForm):
    
        # use = fld.CharField()
    
        class Meta:
            model = models.UserInfo
            fields = "__all__"    
            # fields = ['username','nickname',]
            # exclude = ['username',]
            # error_messages = {
            #     "username": {'required':'用户名不能为空'}
            # }
            # widgets = {
            #     "username":wid.Textarea(attrs={'class':'c1'})
            # }
            # labels = {
            #     'username':'用户名'
            # }
            # help_texts = {
            #     'username': '别瞎写,瞎写打你哦'
            # }
            #
            # field_classes = {
            #     'username': fld.EmailField
            # }
    
        # def clean_email(self):
        #     pass
        #
        # def clean_nickname(self):
        #     pass
        #
        # def clean(self):
        #     pass
    

    在view里面写添加函数,并且将实例化的model_form传给前端

    def user_add(request):
        # 现在的你# 创建Form类:
        if request.method == 'GET':
            model_form = UserModelForm()
            return render(request,'rbac/user_add.html',{'model_form':model_form})
        else:
            model_form = UserModelForm(request.POST)
            if model_form.is_valid():
                model_form.save()   # 添加的话,直接save就行了
                return redirect('/rbac/users.html')
    
            return render(request, 'rbac/user_add.html', {'model_form': model_form})
    

    然后就可以在前端快速生成form

        <form method="POST" novalidate>
            {% csrf_token %}
            {{ model_form.as_p }}
            <input type="submit" value="提交" />
        </form>
    

    修改

    def user_edit(request,pk):
        obj = models.UserInfo.objects.filter(pk=pk).first()
    
        if not obj:
            return redirect('/rbac/users.html')
        if request.method == 'GET':
            model_form = UserModelForm(instance=obj)
            return render(request,'rbac/user_edit.html',{'model_form':model_form})
        else:
            model_form = UserModelForm(request.POST,instance=obj)
            if model_form.is_valid():
                model_form.save()
                return redirect('/rbac/users.html')
            return render(request, 'rbac/user_edit.html', {'model_form': model_form})
    

    相关文章

      网友评论

          本文标题:ModelForm使用方法

          本文链接:https://www.haomeiwen.com/subject/rnosyxtx.html