In Part 3, we added login, logout, and user registration. Now in Part 4, you’ll learn how to create a custom user profile and assign permissions or roles using Django’s powerful auth system.
What You’ll Learn
- Create a profile model linked to the user
- Assign and check user permissions
- Display profile info in templates
Step 1: Create the Profile Model
Create a profile model in models.py
:
1 2 3 4 5 6 7 8 9 10 |
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True) profile_pic = models.ImageField(upload_to='profiles/', blank=True) def __str__(self): return f"{self.user.username} Profile" |
Then run:
1 2 |
python manage.py makemigrations python manage.py migrate |
Step 2: Auto-Create Profile After Registration
In signals.py
inside your app:
1 2 3 4 5 6 7 8 9 |
from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) |
Then connect the signals in apps.py
:
1 2 |
def ready(self): import myapp.signals |
Step 3: Display Profile Information
Create a view in views.py
:
1 2 3 4 5 |
from django.contrib.auth.decorators import login_required @login_required def profile(request): return render(request, 'myapp/profile.html') |
Add URL in urls.py
:
1 |
path('profile/', views.profile, name='profile'), |
Create templates/myapp/profile.html
:
1 2 3 |
<h2>Welcome {{ user.username }}</h2> <p>Bio: {{ user.profile.bio }}</p> <img src="{{ user.profile.profile_pic.url }}" alt="Profile Picture" /> |
Step 4: Add and Check Permissions
Django supports groups and permissions. In the admin panel:
- Create a group (e.g. “Editors”)
- Assign specific permissions (e.g. can add/change Post)
- Add users to the group
Check permissions in a view:
1 2 3 4 |
if request.user.has_perm('myapp.change_post'): # allow edit else: return HttpResponse("You don't have permission.") |
Optional: Restrict Templates Based on Group
1 2 3 |
{% if user.groups.all.0.name == 'Editors' %} <a href="{% url 'create_post' %}">New Post</a> {% endif %} |
Conclusion
Now you’ve extended Django’s default User model by adding a profile and used the built-in permission system to control access. This sets you up to build dashboards, admin tools, or user roles for different types of users.
Next up in Part 5: Build a blog-style dashboard and let users manage their own content.