Django【进阶】modelform
modelform:models+form
建议尽量用Djangoform,更灵活,但也有人用modelform,写起来很简单
缺点,在models里面,表模型必须有__str__()方法
可添加钩子,用法一样
注释部分根据需求选择添加,其他为必须有的。
class UserModelForm(ModelForm): 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
增加和修改,删除简单不示例。
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() return redirect('/rbac/users.html') return render(request, 'rbac/user_add.html', {'model_form': model_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})
template
# 表格: <body> <a href="/rbac/user/add.html">添加</a> <table border="1"> {% for row in user_list %} <tr> <td>{{ row.pk }}</td> <td>{{ row.nickname }}</td> <td>{{ row.username }}</td> <td> <a href="/rbac/user/edit/{{ row.pk }}.html">编辑</a> </td> </tr> {% endfor %} </table> </body> # 添加: <body> <h1>添加用户</h1> <form method="POST" novalidate> {% csrf_token %} {{ model_form.as_p }} <input type="submit" value="提交" /> </form> </body> # 修改: <body> <h1>编辑用户</h1> <form method="POST" novalidate> {% csrf_token %} {{ model_form.as_p }} <input type="submit" value="提交" /> </form> </body>