开发者

Django - Common Cleaning Data

开发者 https://www.devze.com 2023-03-20 18:57 出处:网络
I have one model, and 3 different forms that use this model (of course, each form have different fields of this model). I wrote several clean function to valid the form fill... But, I really dont want

I have one model, and 3 different forms that use this model (of course, each form have different fields of this model). I wrote several clean function to valid the form fill... But, I really dont want copy and past this validation to all forms.

Is it possible to have one common 开发者_如何学运维cleaning class? How can I call it?

Here is the actual code:

models.py

class UserProfile(models.Model):      

    user = models.ForeignKey(User, unique=True)

    cpf = models.CharField('CPF', max_length=14, blank=True)
    cnpj = models.CharField('CNPJ', max_length=18, blank=True)

...

forms.py

 class yyyyyForm(UserCreationForm):  
           ...
           def Meta:
              ...
           def Save:
              ...
           def clean_cpf(self):
              ...

class xxxxxForm(UserCreationForm):  
   ...
   def Meta:
      ...
   def Save:
      ...
   def clean_cpf(self):
      ...


Why don't you have one baseForm class where you put the clean_cpf() method and then extend that for the other forms, and since clean_cpf is in the parent form, you shouldn't have to implement it in the child classes.

In your example it looks like you have a base class called UserCreationForm if that is your form that you can edit then you can put your clean method there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号