nitroman
nitroman

Reputation: 673

How to check whether a user created successfully in Django

I was trying Django and I used this code to create a user

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User    

def register(request):
    user = User.objects.create_user('John', '[email protected]', 'johnpassword')
    user.last_name = "James"
    user.is_active = True
    status = user.save()
    return HttpResponse(status)

My question is how can I check whether a user is successfully created or not and also to display an error message, if I am unable to create a user. When I run this code, it creates a user but returns a value None

Thanks

Upvotes: 2

Views: 3290

Answers (2)

Exelian
Exelian

Reputation: 5888

Check if the user has a pk attribute with an actually value. If it does it's saved in the database.

As user knbk stated below as simple check like the following will be enough

if user.pk is not None: # do stuff

Upvotes: 4

zymud
zymud

Reputation: 2249

create_user will rise integrity error if such user already exists.

def register(request):
    try:
        user = User.objects.create_user('John', '[email protected]', 'johnpassword')
    except IntegrityError:
        # user already exists
        status = 'user already exists'
    else:
        user.last_name = "James"
        user.is_active = True
        user.save()
        status = 'new user was created'
    return HttpResponse(status)

This looks better for me:

def register(request):
    try:
        # user is active bu default
        user = User.objects.create_user('John', '[email protected]', 'johnpassword', last_name='James')
    except IntegrityError:
        # user already exists
        status = 'user already exists'
    else:
        status = 'new user was created'
    return HttpResponse(status)

Upvotes: 2

Related Questions