On Sep 5, 1:11 pm, TheShark <[EMAIL PROTECTED]> wrote:
> I am playing with a Django project which will deal with networking
> information. I would like to enforce some additional constraints above
> and beyond what the default Form fields provides.
>
> For example, if I have a model to represent a 'subnet' it would have
> both a network address (which I can save as an IPAddressField) and a
> netmask which can be an IntegerField. I want to enforce that the host
> portion of the address field is all zeros. This is pretty easy to
> calculate given the address and netmask. But where should I put such
> calcuations?
>
> Class Subnet(models.Model):
> address = models.IPAddressField()
> netmask = models.IntegerField()
>
> In reading the documentation I can find several places where it might
> fit:
> 1) define a new custom Field subclass which incorporates both the
> address and netmask as a single value. This would work, but I think I
> might end up with a lot of extra new Field types and doesn't really
> seem to be the right place.
> 2) override the 'save()' method on my Model subclass, and do the check
> there. This seems pretty easy, but I'm not sure what to do if I fail
> the validation. Raise ValidationError? Either way, this is the option
> I'm leaning towards now.
If you raise an exception here, there's no standard way of showing a
message to the user.
> 3) catch the django.db.models.signals.pre_save signal. I haven't
> played with signals though so I don't know how to set it up. I would
> still have the question of what to do if I fail the validation.
Yes, this doesn't give you anything different from option #2 above.
> 4) Use the clean_address() method of a custom ModelForm. This is
> pretty easy, and feels like it's sort of the right place because then
> I can easily give the user a nice error message. On the other hand,
> it's not really preventing the creation of invalid Subnet instances
> via other methods (say via the Admin interface).
This is a good way to go. The admin interface does allow you to
specify a custom ModelForm:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form
In order to benefit from the clean_address() validation, you will just
need to ensure that all your application code uses this custom
ModelForm to create and update your model instances.
-Rajesh D
--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---