V
V
vfvnvsyevsky2015-02-25 00:36:58
Django
vfvnvsyevsky, 2015-02-25 00:36:58

How to check if a username exists in Django?

I did a manual check from the database:

if request.POST:
    username = request.POST.get('username', '')
    try:
      User.objects.get(username=username)
      args['alert'] = 'Есть'
    except User.DoesNotExist:
      args['alert'] = 'Нет'

but something tells me there is a more elegant way

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2015-02-25
@dizballanze

Something like this is possible:

if User.objects.filter(username=username).exists():
    # OK
else:
    # Not OK

But your way is fine too.

L
leclecovich, 2015-02-25
@leclecovich

In most cases, it doesn't make sense to pass the username in the request body. If you are using a django
authentication system, then you can take the user instance from the request: request.user 1.7/topics/auth/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question