Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 77 ยท Projects

Project: Multi-Role Management System (HOD / Staff / Student)

Build a multi-role Django system with a custom user model, role-based access mixins, attendance and results models and per-role dashboards, running on real migrations.

Many real applications have different kinds of users who see different things: a school, a clinic, a company intranet. In a college system the Head of Department (HOD) manages courses and staff, staff members take attendance and enter marks for their own subjects, and students can only read their own attendance and results. One login page serves everybody, and what happens after login depends on the user's role.

This project builds that backbone. It combines ideas from earlier lessons: a custom user model, permissions and authorization, class-based views, relationships and aggregation. Unlike most examples in this tutorial, the code runs as a real app package: the examples write models.py, views.py and friends to the in-browser file system, run the real makemigrations and migrate, and then send requests to the views.

The design

flowchart TB
    L["Login"] --> H{"user.role"}
    H -- hod --> HD["HOD dashboard<br/>courses, staff, students"]
    H -- staff --> SD["Staff page<br/>mark attendance, enter marks<br/>for OWN subjects"]
    H -- student --> ST["Student report<br/>own attendance %, own marks"]

A single role field decides where each user lands and which pages they may open.

Model Purpose
User A custom user (AbstractUser) with a role field: hod, staff or student
Course A programme such as CS101
Student Links a student User to a Course and a roll number
Subject A subject in a course, taught by one staff User
Attendance One row per student, subject and day, with a present flag
Result A student's marks in a subject

Decision 1: one user model with a role, not three user models

There are two common designs. You can create separate models (HodUser, StaffUser, StudentUser), or keep one User model with a role field and add profile models (such as Student) for role-specific data. The one-model design wins here: Django's login, sessions, admin and permissions all work with a single AUTH_USER_MODEL, and checking request.user.role is trivial. Role-specific data goes into small related models.

Set the user model before the first migration (changing it later is painful; see Custom User Models), and use TextChoices so the allowed roles are defined once:

Python
# settings.py (read-only)
AUTH_USER_MODEL = "college.User"

Decision 2: protect views with a role mixin

Every dashboard needs the same rule: "logged-in users with one of these roles only." Write it once as a mixin and list the allowed roles on each view:

Python
# college/mixins.py (shown in full in the example below)
class RoleRequiredMixin(LoginRequiredMixin):
    allowed_roles = ()

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated and request.user.role not in self.allowed_roles:
            raise PermissionDenied("Your role cannot open this page.")
        return super().dispatch(request, *args, **kwargs)

An anonymous visitor goes to the login page (the behaviour of LoginRequiredMixin). A logged-in user with the wrong role gets 403 Forbidden, which is more accurate than a 404 because the page exists but is off limits. See Error Pages and Exceptions for customizing the 403 page.

Decision 3: always scope data to the caller

The most important security rule in a multi-role system: never trust an id from the URL or form to decide whose data to show. The student report does not take a student id at all; it uses request.user.student. The staff attendance view loads the subject with Subject.objects.get(pk=..., staff=request.user), so a staff member cannot touch a colleague's subject even by guessing the id. This pattern (filter by the current user inside the query) prevents the classic "change the number in the URL and see someone else's record" bug.

Part 1: models, migrations and constraints

The first example creates the app package, runs makemigrations and migrate, seeds users, and tests the guarantees that live in the database rather than in view code: a unique constraint stops a duplicate attendance mark, and limit_choices_to restricts the teacher drop-down to staff.

Python Models, real migrations, roles and constraints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice limit_choices_to={"role": "staff"}: in a form, the teacher menu offered only mia, not the HOD or the student. It filters forms and the admin, but it does not stop code from saving a non-staff user as the teacher, so validate in your views or in clean() when it matters. The UniqueConstraint on (student, subject, date) is different: it is enforced by the database for every code path.

Part 2: role-protected views end to end

The second example adds the mixin, three views and URLs, then plays through a day in the life: anonymous and wrong-role access, role-based redirects, a staff member marking attendance, a staff member blocked from a colleague's subject, and students reading their own reports. Attendance is stored as one row per student per day; the percentage is computed in the database with a conditional Count.

Python The complete role-based app: dashboards, attendance and results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the printed lines as a permission matrix:

Request Result Why
Anonymous GET /hod/ 302 to /login/?next=/hod/ LoginRequiredMixin
Student GET /hod/ 403 role not in allowed_roles
HOD GET /hod/ JSON counts allowed
GET / as hod, staff, student three different redirects home() looks at user.role
Staff POST /staff/ for own subject saved rows staff=request.user in the lookup
Staff POST /staff/ for a colleague's subject Subject.DoesNotExist (in production, return 404) the lookup is scoped to the caller
Student GET /student/ only that student's data request.user.student, no id in the URL

update_or_create makes the attendance form safe to submit twice: marking the same day again updates the existing rows (the unique constraint guarantees there is only one) instead of creating duplicates. Sam attended all three Maths classes (100%), while Tia attended one of three (33%).

Extending the project

  • Real pages. Replace JsonResponse with templates and forms. A ModelForm for Result and a formset for the attendance sheet fit naturally.
  • Shortage list for the HOD. Annotate students with their attendance percentage and filter < 75 to find who needs a warning. This is one query with annotate and filter (see Aggregation and Annotation).
  • Admin. Register each model, restrict the HOD's staff-management screens with groups and permissions (see Customizing the Admin), and leave attendance entry to staff views.
  • Notifications. When marks are saved, send the student an email from a signal or a background task.
  • Auditing. Keep created_by and updated_at columns so you can answer "who changed this mark?"
  • Automate the role guard in tests. One parametrized test that requests every URL as every role gives you a permission matrix that cannot silently regress (see Testing Patterns).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use one User model with a role field instead of three separate user models?

    Django authentication is built around one user model. A role field plus small profile models gives you different data per role without duplicating the login machinery.
  2. 2. What status should a logged-in student get when opening the HOD dashboard?

    The student is authenticated but not allowed. 403 expresses that; the login redirect is for anonymous visitors.
  3. 3. Why does the student report use request.user.student instead of a student id from the URL?

    Never use client-supplied ids to decide whose data to show. Scope queries to the current user.
  4. 4. What does the UniqueConstraint on (student, subject, date) guarantee?

    Constraints are enforced by the database for every code path, unlike checks written in views.

Summary

  • Model roles with one custom User (role as TextChoices) and put role-specific data in related models; set AUTH_USER_MODEL before the first migration.
  • Guard views with a reusable RoleRequiredMixin: anonymous users go to login, wrong roles get 403.
  • Always scope data to the caller (request.user.student, staff=request.user) instead of trusting ids from the client.
  • Let the database enforce invariants with unique constraints, and use update_or_create and conditional Count for attendance and percentages.
  • Test the role-by-URL permission matrix, and grow the project with templates, forms, groups and notifications.

Next: Project: Word Counter and CGPA Calculator.