Re: ensuring uniqueness in newforms

2008-04-01 Thread Jonathan Buchanan

On Tue, Apr 1, 2008 at 4:00 AM, msoulier <[EMAIL PROTECTED]> wrote:
>
>  If I have a field, for example a CharField named 'name', which must be
>  unique, what's the best way to ensure uniqueness whether creating a
>  new entry or editing an existing one?
>
>  By default, the form won't know if it is being used to edit or create,
>  so if you look for duplicates in the db, how would you know whether
>  any dup you found is just the current entry being edited?
>
>  Or is the form the wrong place for this kind of thing? Should this
>  instead be enforced in the model, and we should instead catch the
>  exception throw during the save attempt? I'm guessing not, as I was
>  once told that validation in the model is deprecated.
>
>  Thanks,
>  Mike

Assuming that when you're editing, the instance being edited is being
held as an "instance" attribute of the form, or None otherwise:

def clean_name(self):
try:
obj = YourModel.objects.get(name=self.cleaned_data['name'])
if not self.instance or obj.pk != self.instance.pk:
raise forms.ValidationError(u'This name is already taken.')
except YourModel.DoesNotExist:
pass
return self.cleaned_data['name']

You could trim it down to only pull back the pk of any existing
object, but that's the gist of it.

IIRC, model validation is still being worked on. I've not been in the
loop lately, so I can only suggest searching the list :)

Regards,
Jonathan.

--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



ensuring uniqueness in newforms

2008-03-31 Thread msoulier

If I have a field, for example a CharField named 'name', which must be
unique, what's the best way to ensure uniqueness whether creating a
new entry or editing an existing one?

By default, the form won't know if it is being used to edit or create,
so if you look for duplicates in the db, how would you know whether
any dup you found is just the current entry being edited?

Or is the form the wrong place for this kind of thing? Should this
instead be enforced in the model, and we should instead catch the
exception throw during the save attempt? I'm guessing not, as I was
once told that validation in the model is deprecated.

Thanks,
Mike
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---