-1

I use from django.contrib.auth.forms import UserCreationForm in forms.py for creating sign up form. first I register with a username, for example ali and again when I try to register with Ali it allows me to create user. how can I prevent registering with two same username like Ali and ali ?

Ali Soltani
  • 589
  • 1
  • 7
  • 21

2 Answers2

0

What I would do is override the UserCreationForm, and write a custom validation to check if that username__iexact already exists, and if so, raise a validation error

Dalvtor
  • 3,160
  • 3
  • 21
  • 36
  • I tried this but doesn't work: ` def clean_username(self, username): username = self.cleaned_data['username'] if User.objects.get(username__iexact=self.cleaned_data['username']): raise forms.ValidationError("This username has already existed.") return username` – Ali Soltani Feb 08 '18 at 10:48
0

This worked for me:

def clean_username(self):
    username = self.cleaned_data['username']
    username1=str(username)
    username1=username.lower()
    if User.objects.filter(username=username1).exists():
        self._errors["username"] = ErrorList([u"username exists"])
Ali Soltani
  • 589
  • 1
  • 7
  • 21