将fields字段设置为all来展示所有的字段

  1. fields = '__all__'
  1. class AuthorForm(forms.ModelForm):
  2. class Meta:
  3. model = Author
  4. fields = ['author_name', 'email']

默认显示Author模型中所有字段,使用fields指定要显示的字段名,使用exclude指定要排除的字段。

视图渲染

在元数据中使用widgets属性

  1. class AuthorForm(forms.ModelForm):
  2. class Meta:
  3. model = Author
  4. widgets = {
  5. 'password': forms.PasswordInput(attrs={'class':'myclass'})
  6. }

在初始化函数中

  1. class AuthorForm(forms.ModelForm):
  2. def __init__(self, *args, **kwargs):
  3. super().__init__(*args, **kwargs)
  4. self.fields['password'].widget = forms.PasswordInput()
  5. class Meta:
  6. model = Author

定义展示的信息,labels属性

  1. class Meta:
  2. model = Author
  3. labels = {
  4. 'author_name':_('作者姓名'),
  5. }

输入提示的信息,help_texts属性

  1. class Meta:
  2. model = Author
  3. help_text = {
  4. 'author_name':_('输入纯英文组成的作者姓名')
  5. }

输入展示的错误信息,error_messages属性

数据提交

  1. # views.py
  2. author = AuthorForm(request.POST)
  3. if author.is_valid():
  4. author.save()

数据展示

  1. #views.py
  2. author = Author.objects.get(pk=author_id)
  3. author_form = AuthorForm(instance=author)
  4. #print(author_form.instance.id), 可以使用instance属性获取Author实例对象
  5. return render(request, 'show_author.html', {'author_form': author_form})

更新数据

  1. #views.py
  2. author = Author.objects.get(pk=author_id)
  3. author_form = AuthorForm(request.POST, instance=author)
  4. if author_form.is_valid():
  5. author_form.save()

自定义验证规则

  1. class UserRegisterForm(forms.ModelForm):
  2. confirm_passwrod = forms.CharField(widget=forms.PasswordInput)
  3. def clean_confirm_password(self):
  4. password = self.cleaned_data['password']
  5. confirm_password = self.cleaned_data['confirm_password']
  6. if password!=confirm_password:
  7. raise form.ValidtionError('两次密码不一致')
  8. return self.confirm_password
  9. class Meta:
  10. model = User