views:

847

answers:

1

I realize this has been asked before, but I wasn't able to find a question that really dealt with what I'm trying to do. I think it's pretty simple, but I'd like to know what the general population thinks is best form here.

Lets say we have the following:

models.py

class TestClass(models.Model):
    user = models.ForeignKey(User)
    testfield = models.CharField()
    testbool = models.BooleanField(default=False)

def save(self, *args, **kwargs):
    """
    - what we're trying to do here is ensure that the User doesn't have more than
      X (lets say 5) related test fields.
    - what if we also wanted to add validation to testfield to ensure it was 
      only [a-zA-Z]?
    """
    if TestClass.objects.filter(user=self.user).count() >= 5:
        # How do we exit gracefully?
        return 
    super(TestClass, self).save(*args, **kwargs)

The comments in the save function pretty much sum up my question: - How would we ensure that there aren't more than 5 related TestClass's to the giving user - How do we exit gracefully from save (without saving) if there are already 5 - How do we report this back to the user? - where do we validate the testfield object to ensure it only has [a-z]? can I just import re and do that here as well? should i?

Is it best to throw this all in here? Should I fire off a pre_save signal? Or should I just use a ModelForm w/ validation?

A: 

You're right that there's currently no obvious place to do this. That's why there's a Summer of Code project going on right now to add model-level validation, which should make this sort of thing nice and easy.

Unfortunately it won't be ready for a couple of months. In the meantime, your answer depends on how data is being added. Will it ever be done programatically, or will it always be via a form? If the latter, then putting the validation into the form is the way to go (note that you can use the same modelform, or subclasses of it, in both the admin and your own view, so no need to duplicate logic).

Daniel Roseman
If i use this in the admin, will it overwrite the standard validation that the admin does (aka blank=False, proper dates, ect.)?Also; if I want to override save(), whats the best way to exit from that? I'm assuming raising an exception is probably bad... so do i just return False and not give a reason?
lostincode
As long as you don't redefine any of the actual fields, then default validation will work as normal. For save, it doesn't need to return anything, so just returning is fine.
Daniel Roseman