Django

College Event Registration Website

CampusConnect Introduction and Setup Configuring settings file for template, static and media files Setting up Tailwind Creating Custom User Model Creating Super User for CampusConnect Registering Custom User Model Search and Filter for User Model Serving Media Files During Development Categorizing Departments Linking Department with HOD Creating Abstract Model for Event Creating Model for Workshop Customizing Admin Page for Workshop Update in Model AbstractEvent Adding Instructor for Workshop Instructor Model Admin Page Adding Poster Field in Abstract Event Providing Access to HOD Access Update for HOD Restricting HOD Access to Particular Department AbstractEvent On Spot Registration Field Creating Workshop Object Creating and Linking Home Page Displaying Workshop on Home Page Styling Home Page Adding Workshop Detail Page Link Workshop Detail Page Workshop Detail Page Styling Workshop Instructor Details Workshop Detail Contact Contact Admin Page Many to Many Field for Contact Displaying Contact on Workshop Detail Page Adding Title for Workshop Detail Page Adding Gallery for Workshop Workshop Gallery Admin Page Displaying Gallery Images on Website Through Context Displaying Gallery Images on Website through template tags Authentication for users User Registration User Registration Submission Logout Functionality For User Login Functionality for User Model For Workshop Registration Workshop Registration Admin Page Register Workshop Function Register Button in Workshop Page Validations Before Workshop Registration Workshop Registration Closed Validaiton User Already Registered for Workshop Validation Workshop Registration Report From Admin Page Export using Library in Django Admin Extending Abstract Event for Hackathons

Creating Super User for CampusConnect

A superuser in django can be created using the following command :

python manage.py createsuperuser

alt textWhen you try to execute this command, it will give an error like this. This is createsuperuser command requries the username field for creating an object in the database. In order to create a superuser, you would need to override the BaseUserManager class.

This can be done as follows :

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('Users require an email field')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('role', 'a')

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class User(AbstractUser):
    username = None
    email = models.EmailField('Email Address', unique=True)
    profile_photo = models.ImageField(upload_to='profile_photos/', null=True, blank=True,default='profile_photos/default_profile.png')
    mobile_number = models.CharField(max_length=10, null=True, blank=True)
    role = models.CharField(max_length=1, choices=[('a', 'Admin'), ('h', "HOD"), ('s', 'Student')])

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def save(self, *args, **kwargs):
        if not self.password.startswith('pbkdf2_sha256$'):
            self.password = make_password(self.password)
        super().save(*args, **kwargs)

Here, we are overriding the functions inside the BaseUserManager class to accept email field and create users based on that field.

Now, when you try to createsuperuser you won't get that error.

python manage.py createsuperuser

alt text And here superuser has been created successfully. You can use this to login inside the admin portal. First you would need to start the server which can be done using the following command :

python manage.py runserver 0.0.0.0:8000

here 0.0.0.0 refers to the ip at which the project is launched 0.0.0.0 means it can be served on any ip address and 8000 is the port number at which it is served.

alt text Now you can go to admin page by visiting the following url : http://localhost:8000/admin/login/?next=/admin/ alt textBy typing the email and password, you would be able to login to the website. alt textYou would get a page like this when you login to the admin site. Here still the custom User model is not visible as it has not been registered inside the admin portal. The Groups model that is being displayed here is used to provide access permissions for users in Django and is a default model created by django.

In the next module, you will see how you can register, view and edit User model through admin page.