Well,

MAX_CUISINES = 3

def clean(self):
        # three cuisines max. allowed
        if self.pk is None:
            # That's the case that raise the error
            # you're inserting a new Restaurant
            pass
        else:
            # Here, you're editing an existing Restaurant
    # (including its relashionship with Cuisine)
            if self.cuisines.count() > MAX_CUISINES:
raise ValidationError('I said, "Choose up to three" cusines!')

As we're aiming to prevent, at model's level, saving a new Restaurant when too many related Cuisine are provided, I'm afraid that doesn't fit the needs... unless saving restaurant's intance, run a validation then delete it if it fails the validation :) I'd like to place the validation at 'cusines' field level. I'm not confortable placing it at the "whole" model's level, despite my suggestion.

I failed for the moment to find a way and I'll resume tomorrow. Maybe the following unsuccessful tries can help you (with a mix of admin interface playing and shell, both on dev server):

  * use validator on models.ManyToManyField:

      I can't even trigger a simple print('test') TT

* use a custom field by extending models.ManyToManyField, overriding its isValidIDList method

Ok, it is a blind test: I was looking for a way to access values from cuisines for a non saved instance of Restaurant and maybe something is lurking there. I'm a beginner.

* accessing self's attributes for a non saved or retrieved instance of Restaurant

      # desesperately random commands (I tried more :):

      u = Restaurant()
      r = Restaurant.objects.all()[0]

      dir(u)
      # hey, a "cuisines" attribute, great!
      dir(u.cuisines)
      # TT, same error you encountered
      dir(r.cuisines)
      # fine

      u.clean_fields()
      # 'cusines' is not even mentionned in the error message
      r.clean_fields()
      # fine

      [f.verbose_name for f in r._meta.fields]
      # no cusines

I believe that no control is enforced before saving, but if you try to create an new Restaurant and not provide a cuisine, the validation failed from the admin. How does it handle that? I'll try to find out. Is there a way to access data provided to 'cuisines' for an unsaved Restaurant?

Regards,

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to