Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if username exists in Django

Tags:

I am working on a Django project where users will be able to change their usernames along with their first and last name in one form. In forms.py, I am trying to find out if the user exists. If so, it should display an error.

The problem is that if user wants to change his first and last name and leaves his username in the input, it raises a validation error. Obviously, that username already exists.

Is there a way to check if it equals the username of currently logged user and avoid displaying the error?

class ChangeNameForm(forms.ModelForm):
    username = forms.CharField(max_length=30)
    first_name = forms.CharField(max_length=255)
    last_name = forms.CharField(max_length=255)

    def clean_username(self):
        username = self.cleaned_data['username']

        try:
            user = User.objects.get(username=username)
        except user.DoesNotExist:
            return username
        raise forms.ValidationError(u'Username "%s" is already in use.' % username)
like image 328
lukas Avatar asked Nov 15 '13 20:11

lukas


People also ask

How to check username already exists in django?

objects. filter(username=self. cleaned_data['username']). exists(): # Username exists ...

How do you check email is exist or not in Django?

objects. filter(username=username). exists() if not user_exist: # create your user new_user = User(username=username) new_user. email = email new_user.


1 Answers

When ModelForms are bound to a model object, they have an attribute called 'instance', which is the model object itself. In your view, when request.method == 'POST', you're probably creating the form instance like this:

form = ChangeNameForm(request.POST, instance=request.user)

If that's the case, you can access the logged user from the form methods, and your validation method can be something like this:

def clean_username(self):
    username = self.cleaned_data['username']
    try:
        user = User.objects.exclude(pk=self.instance.pk).get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(u'Username "%s" is already in use.' % username)

Consider using the .exists method, for it issues a faster query to your database than if you try to retrieve all the user information with the .get method. And the code gets a little cleaner too:

def clean_username(self):
    username = self.cleaned_data['username']
    if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists():
        raise forms.ValidationError(u'Username "%s" is already in use.' % username)
    return username

Optionally, you can also follow these guidelines when raising the ValidationError.

I can't test this code right now, so I apologize if there's anything wrong.

like image 183
Victor Silva Avatar answered Oct 01 '22 01:10

Victor Silva