Hi Preston, On 04/02/2015 10:15 AM, Preston Timmons wrote: > Since I think this can be a useful feature, I'll explain why. > > One use case is for validating address forms. We deal with a lot of > them with varying levels of validation based on country, state, zip > code, etc. Sometimes, multiple sets of address fields appear on the > same form. We can't simply reuse the fields without worrying about > disparate validation routines specified on the form in addition to the > fields. This leads to a meticulous set of mixins. It gets the job done, > but I don't think that's great api. > > If fields had a second clean method that was called with the form > data, we could do something simpler like: > > state1 = StateField(country_field="country1") > state2 = StateField(country_field="country2") > > The field would then look like: > > StateField(): > > def __init__(self, country_field=None): > self.country_field = country_field > > def clean_full(self, cleaned_data): > if self.country_field: > do_something(cleaned_data[country_field]) > > Yes, clean_FOO() can be made to work. No, it doesn't make reusing > fields with complex validation in multiple forms and contexts easy, > especially if the field names may need to differ in certain forms.
As I said earlier in the thread, I think it's entirely possible to build this, in a fully generic and reusable way, on top of current Django core as a third-party add-on. It could even have the exact API you propose. You just need a `Form` subclass with a `clean` method that loops through the fields on the form and calls the `clean_full` method (if it exists) on each of them. I think the "frequency of need" vs "added complexity" calculation does not come out in favor of adding this to Django core, but I don't see any reason it can't exist as a third-party utility. I also find it a mild violation of field encapsulation for fields to know about other fields on the same form. In my mind, the right level of abstraction for cases like this is usually to build a reusable `AddressForm`, which does cross-field validation at the form level, and then reuse that alongside other forms. (In general, I think users of Django's forms library often don't take enough advantage of the fact that a single HTML form doesn't need to be a single Django `Form` class.) Carl -- You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscr...@googlegroups.com. To post to this group, send email to django-developers@googlegroups.com. Visit this group at http://groups.google.com/group/django-developers. To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/551D6FAE.507%40oddbird.net. For more options, visit https://groups.google.com/d/optout.
signature.asc
Description: OpenPGP digital signature