2013-04-26 17 views
7

stworzyłem niestandardowy formularz z niestandardowych walidacji tak:Django jak zastąpić metodę clean() w podklasie niestandardowej postaci?

class MyCustomForm(forms.Form): 
    # ... form fields here 

    def clean(self): 
     cleaned_data = self.cleaned_data 
     # ... do some cross-fields validation here 

     return cleaned_data 

Teraz, ta forma jest podklasy z innej formie, która posiada własną czystą metodę.
Jaki jest prawidłowy sposób wyzwalania obu metod clean()?
W tej chwili jest to, co robię:

class SubClassForm(MyCustomForm): 
    # ... additional form fields here 

    def clean(self): 
     cleaned_data = self.cleaned_data 
     # ... do some cross-fields validation for the subclass here 

     # Then call the clean() method of the super class 
     super(SubClassForm, self).clean() 

     # Finally, return the cleaned_data 
     return cleaned_data 

wydaje się działać. Jednak powoduje to, że dwie metody clean() zwracają cleaned_data, co wydaje mi się nieco dziwne.
Czy to jest właściwy sposób?

+0

Robisz go poprawnie. –

Odpowiedz

12

to zrobić dobrze, ale trzeba załadować cleaned_data z Super rozmowy tak:

class SubClassForm(MyCustomForm): 
# ... additional form fields here 

def clean(self): 
    # Then call the clean() method of the super class 
    cleaned_data = super(SubClassForm, self).clean() 
    # ... do some cross-fields validation for the subclass 

    # Finally, return the cleaned_data 
    return cleaned_data 
+0

Dzięki @Mounir. Jedno pytanie: sposób w jaki sugerujesz, "cleaned_data" będzie zawierał pola z super klasy. Muszę również sprawdzić poprawność pól w podklasie. Jak mam to zrobić? – user1102018

+0

, aby kontynuować mój komentarz, może powinno być coś takiego: 'cleaned_sub_data = self.cleaned_data', a następnie' cleaned_data.update (cleaned_sub_data) '. Wtedy mogę zwrócić 'cleaned_data' – user1102018

Powiązane problemy