好的,所以我有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的答案,创建一个基本表单,并让UserUpdateFormRegistrationForm扩展您的基本表单。

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_emailUserUpdateForm对象都可以使用RegistrationForm方法。

有关表单继承的更多信息,请浏览docs.

更新:

如果您需要在子类中更改方法,则可以覆盖它,但是可以像下面这样包含对superclean_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/

10-09 17:19