views:

242

answers:

1

I do not care about concurrency issues.

It is relatively easy to build unique form field:

from django import forms

class UniqueUserEmailField(forms.CharField):
    def clean(self, value):
      self.check_uniqueness(super(UniqueUserEmailField, self).clean(value))

    def check_uniqueness(self, value):
        same_user = users.User.all().filter('email', value).get()
        if same_user:
          raise forms.ValidationError('%s already_registered' % value)

so one could add users on-the-fly. Editing existing user is tricky. This field would not allow to save user having other user email. At the same time it would not allow to save a user with the same email. What code do you use to put a field with uniqueness check into ModelForm?

A: 

quick and dirty way would be:

  1. make check_uniqueness classmethod
  2. use custom field check in ModelForm, like this:

    class User(forms.ModelForm):    
        email = forms.EmailField()    
    def clean_email(self):
        data = self.cleaned_data['email']
        original = self.instance.email
        if original == data:
            return data
        UniqueUserEmailField.check_uniqueness(data)
        return data
    

better options?

Alexander Vasiljev