python - 如何通过继承避免 ModelForms 中的代码重复

标签 python django inheritance django-forms

好的,我有了 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_email 方法现在可用于 UserUpdateFormRegistrationForm 对象。

有关表单继承的更多信息,请浏览 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/

相关文章:

python - Django ;如何在没有模板的情况下创建 View (函数)

c# - 接口(interface)中的函数,返回实现它的任何类的类型的对象

java - 只允许某些类访问私有(private)变量的接口(interface)

python - Django模型设计

python - python中的heapq和PriorityQueue有什么区别?

Python 多处理示例不起作用

python - 记录更改列表中的 Django-admin : How to display link to object info page instead of edit form ,?

python - 在 Django 中查询模型(两层深度)

flutter - 为什么Flutter框架源代码中的类没有扩展Object类?

python - pip : was OK for months now :ImportError: No module named 'pip._vendor.requests.adapters'