Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of get_or_create for adding users

Tags:

Is there a simpler way to add a user than with the following pattern?

    try:         new_user = User.objects.create_user(username, email, password)     except IntegrityError:         messages.info(request, "This user already exists.")     else:         new_user.first_name = first_name         # continue with other things 
like image 810
David542 Avatar asked Sep 22 '11 07:09

David542


2 Answers

In Django 1.4, get_or_create() exists for User.

from django.contrib.auth.models import User  _user = User.objects.get_or_create(         username=u'bob',         password=u'bobspassword',     ) 
like image 172
nu everest Avatar answered Oct 11 '22 02:10

nu everest


It is better not to catch IntegrityError as it can happen for other reasons. You need to check if user exists, excluding the password. If user already exists, set the password.

user, created = User.objects.get_or_create(username=username, email=email) if created:     user.set_password(password)     user.save() 
like image 32
Pandikunta Anand Reddy Avatar answered Oct 11 '22 02:10

Pandikunta Anand Reddy