Django Create User

Managing users in Django applications

👤 Creating Users in Django

Django provides built-in user management system. You can create users programmatically, through admin interface, or via command line. Django handles password hashing and authentication automatically for security.


# Create a user programmatically
from django.contrib.auth.models import User

user = User.objects.create_user('john', '[email protected]', 'password123')
                                    

User Creation Methods

⌨️

Command Line

Create users via terminal

python manage.py createsuperuser
🖥️

Admin Interface

Use Django admin panel

# Access at /admin/
# Add user manually
💻

Programmatically

Create users in Python code

User.objects.create_user()
📝

Registration Form

Let users register themselves

UserCreationForm

🔹 Create User with create_user()

The create_user() method is the recommended way to create users programmatically. It automatically hashes passwords and sets required fields. This method ensures security best practices are followed when creating user accounts.

# In Django shell or views.py
from django.contrib.auth.models import User

# Create a regular user
user = User.objects.create_user(
    username='johndoe',
    email='[email protected]',
    password='securepass123'
)

# Set additional fields
user.first_name = 'John'
user.last_name = 'Doe'
user.save()

print(f"User {user.username} created successfully!")

🔹 Create Superuser

Superusers have all permissions and can access the admin interface. Use create_superuser() method to create admin accounts programmatically, or use the management command for interactive creation with prompts.

# Method 1: Programmatically
from django.contrib.auth.models import User

superuser = User.objects.create_superuser(
    username='admin',
    email='[email protected]',
    password='adminpass123'
)

# Method 2: Command line (interactive)
# python manage.py createsuperuser

🔹 User Registration View

Create a registration system for your website allowing visitors to sign up. This view handles form submission, validates user input, creates new user accounts, and redirects to login page upon successful registration.

# views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        
        # Create user
        user = User.objects.create_user(username, email, password)
        messages.success(request, 'Account created successfully!')
        return redirect('login')
    
    return render(request, 'register.html')

🔹 Using UserCreationForm

Django provides a built-in form for user registration that includes validation and password confirmation. UserCreationForm handles common registration requirements like checking username availability and ensuring password strength automatically.

# views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = UserCreationForm()
    
    return render(request, 'register.html', {'form': form})
<!-- register.html -->
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>

🔹 Bulk User Creation

Create multiple users at once using loops or bulk operations. This is useful for testing, importing users from external sources, or setting up demo accounts for your application quickly and efficiently.

# Create multiple users
from django.contrib.auth.models import User

users_data = [
    {'username': 'user1', 'email': '[email protected]', 'password': 'pass1'},
    {'username': 'user2', 'email': '[email protected]', 'password': 'pass2'},
    {'username': 'user3', 'email': '[email protected]', 'password': 'pass3'},
]

for data in users_data:
    User.objects.create_user(**data)
    print(f"Created user: {data['username']}")

🧠 Test Your Knowledge

Which method is recommended for creating users in Django?