将fields字段设置为all来展示所有的字段
fields = '__all__'
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ['author_name', 'email']
默认显示Author模型中所有字段,使用fields指定要显示的字段名,使用exclude指定要排除的字段。
视图渲染
在元数据中使用widgets属性
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
widgets = {
'password': forms.PasswordInput(attrs={'class':'myclass'})
}
在初始化函数中
class AuthorForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password'].widget = forms.PasswordInput()
class Meta:
model = Author
定义展示的信息,labels属性
class Meta:
model = Author
labels = {
'author_name':_('作者姓名'),
}
输入提示的信息,help_texts属性
class Meta:
model = Author
help_text = {
'author_name':_('输入纯英文组成的作者姓名')
}
数据提交
# views.py
author = AuthorForm(request.POST)
if author.is_valid():
author.save()
数据展示
#views.py
author = Author.objects.get(pk=author_id)
author_form = AuthorForm(instance=author)
#print(author_form.instance.id), 可以使用instance属性获取Author实例对象
return render(request, 'show_author.html', {'author_form': author_form})
更新数据
#views.py
author = Author.objects.get(pk=author_id)
author_form = AuthorForm(request.POST, instance=author)
if author_form.is_valid():
author_form.save()
自定义验证规则
class UserRegisterForm(forms.ModelForm):
confirm_passwrod = forms.CharField(widget=forms.PasswordInput)
def clean_confirm_password(self):
password = self.cleaned_data['password']
confirm_password = self.cleaned_data['confirm_password']
if password!=confirm_password:
raise form.ValidtionError('两次密码不一致')
return self.confirm_password
class Meta:
model = User