好的,我有了 UserUpdateForm 和 RegistrationForm。目前各有此功能:
def clean_email(self):
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(pk=self.instance.id).count():
raise forms.ValidationError('Email already in use.')
return email
我想知道避免这种重复的理想方法是什么。
请指教。
**更新**
如果我需要调用父函数,但需要调用所有一些东西怎么办,比如说我有这个:
def clean_email(self):
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(pk=self.instance.id).count():
raise forms.ValidationError('Email already in use.')
### THIS BIT IS ONLY NEEDED IN ONE OF THE CHILD FORMS ###
# Check whether the email was change or not
if self.instance.email != email:
# To not change the email in our database until the new one is verified
return self.instance.email
###
return email
最佳答案
扩展 msc 的答案,创建一个基本表单并让 UserUpdateForm
和 RegistrationForm
扩展您的基本表单。
class YourBaseForm(ModelForm):
def clean_email(self):
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(pk=self.instance.id).count():
raise forms.ValidationError('Email already in use.')
return email
class UserUpdateForm(YourBaseForm):
# ....add unique fields or methods here
class RegistrationForm(YourBaseForm):
# ....add unique fields or methods here
clean_email
方法现在可用于 UserUpdateForm
和 RegistrationForm
对象。
有关表单继承的更多信息,请浏览 docs.
更新:
如果您需要更改子类中的方法,那么您可以覆盖它但包括对 super 的调用像这样的 clean_email
方法 -
UserUpdateForm(YourBaseForm):
def clean_email(self):
email = super(UserUpdateForm, self).clean_email()
if self.instance.email != email:
return self.instance.email
return email
关于python - 如何通过继承避免 ModelForms 中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554837/