How to create a user in Django?

PythonDjango

Python Problem Overview


I'm trying to create a new User in a Django project by the following code, but the highlighted line fires an exception.

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed

    **user = User.objects.create_user(userName, userMail, userPass)**
    user.save()

    return render_to_response('home.html', context_instance=RequestContext(request))

Any help?

Python Solutions


Solution 1 - Python

The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..

from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
                                 email='[email protected]',
                                 password='glass onion')

Solution 2 - Python

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

Solution 3 - Python

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: https://stackoverflow.com/questions/33907663/how-to-use-bcrypt-to-encrypt-passwords-in-django

Tested in Django 1.9.

Solution 4 - Python

If you creat user normally, you will not be able to login as password creation method may b different You can use default signup form for that

from django.contrib.auth.forms import UserCreationForm

You can extend that also

from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    mobile = forms.CharField(max_length=15, min_length=10)
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'email', 'mobile' ]

Then in view use this class

class UserCreate(CreateView):
    form_class = UserForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('list')

    def form_valid(self, form):
        user = form.save()




Solution 5 - Python

If you simply use object.save() to create user, the raw password will be directly visiable inside the database. First, not secure. Second, the encryption of the password is not done, causing the decryptor will use the raw password inside your database to decrypto a wrong password, which makes logging in impossible. I guess every time you use authenticate function from django.contrib.auth, you are actually using the decryptor of it. And yes, I guess everytime you signing in, your password need to get decrypted again.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmr M. AbdulRahmanView Question on Stackoverflow
Solution 1 - PythonkeithhackbarthView Answer on Stackoverflow
Solution 2 - PythonBurhan KhalidView Answer on Stackoverflow
Solution 3 - PythonCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 4 - PythonNids BarthwalView Answer on Stackoverflow
Solution 5 - PythonBoyce CecilView Answer on Stackoverflow