如何使用inheritan避免模型表单中的代码重复

2024-04-26 05:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有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

Tags: andtheinstanceinselfcleandataget
3条回答

使用信号例如:

 models.py

 @receiver(pre_save, sender=User)
 def User_pre_save(sender, **kwargs):
     email = kwargs['instance'].email
     username = kwargs['instance'].username

     if not email: raise ValidationError("email required")
     if sender.objects.filter(email=email).exclude(username=username).count(): raise ValidationError("email is already exist")      

你知道吗视图.py你知道吗

 def view_name(request):
     try:
          .......
     except ValidationError, e:
        message_dict = e.update_error_dict({})
        state = message_dict[NON_FIELD_ERRORS] 
 return render(request, 'page.html', {'state':state}) 

在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.

更新:

如果您需要更改子类中的方法,那么您可以重写它,但包括对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

您可以创建一个具有该函数的基窗体,然后让两个窗体都扩展该函数。你知道吗

相关问题 更多 >