Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Django form Field Unique?

I have a Signup form Where I want to make data of email and mobile Number Field to be Unique....

class SignUpForm(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.', unique=True)
    mobile_no = forms.CharField(validators=[max_length=17, initial='+91', unique=True)  

I am Currently using unique=True but it raise Error as...

TypeError: __init__() got an unexpected keyword argument 'unique'
like image 966
Jayesh Singh Avatar asked Jan 02 '23 18:01

Jayesh Singh


1 Answers

Easiest and fastest way(both for you and server) is to implement it in your model by setting unique=True.
If you want it in form anyway you need to override clean

Cleaning email:

class SignUpForm(UserCreationForm):
    ...

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise ValidationError("Email already exists")
        return email

Now form.is_valid() will throw error if an user account with given email already exists.
I think you can figure out how to do same thing for mobile number now.

like image 200
Vaibhav Vishal Avatar answered Jan 12 '23 23:01

Vaibhav Vishal