steps Flashcards
To create a new project named “djangoappname”
django-admin startproject djangoappname .
Don’t forget to add the . dot at the end of this command. This will actually generate all the files in the current directory
Before starting the server, let’s run the migrations. after creating the CoreRoot project, execute
python manage.py migrate
start the Django server:
python manage.py runserver
set up a postgres database:
> sudo su postgres
> psql
> CREATE DATABASE coredb;
> CREATE USER coreuser WITH PASSWORD ‘wCh29&HE&T83’;
> GRANT ALL PRIVILEGES ON DATABASE coredb TO coreuser;
> ALTER USER core CREATEDB;
how to configure the project to connect to a database.
In the settings.py file:
https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,
‘NAME’: ‘coredb’,
‘USER’: ‘coreuser’,
‘PASSWORD’: ‘wCh29&HE&T83’,
‘HOST’: ‘localhost’,
‘PORT’: ‘5342’,
}
}
run the migrations
python manage.py migrate
to see django logo/running
go to
https://www.educative.io/courses/full-stack-django-and-react/configuring-the-database
second black screen (after db conf and connection)
execute first steps (migration/runserver)
When working with Django, To have a clean and well-organized project,
we’ll have to create many apps to handle different parts of a project.
For example, we can have a different application for authentication, and another for payments or articles.
- django-api
- core
- apps.py
…
- apps.py
- CoreRoot
- settings.py
…
…
- settings.py
- core
At the root of the project, inside “djangoappname” folder, run the following command to Create the core application
- RUN django-admin startapp core
- remove all the files in this app except for the apps.py file and the __init__.py file.
Inside apps.py, add the last line (“label” class property) of the following code:
from django.apps import AppConfig
class CoreConfig(AppConfig):
default_auto_field = ‘django.db.models.BigAutoField’
name = ‘core’
label = ‘core’
Register the app in the INSTALLED_APPS list inside the settings.py file of the project:
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
'core' ]
creating a User application (submodule)
inside”djangoappname” folder
#inside”core”AppFolder
django-admin startapp user
User table structure
public_id: string
last_name: string
first_name: string
username: string
bio: string
avatar: image
email: string
is_active
is_superuser
created: datetime
updated: datetime
in Django ORM:
import uuid
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.http import Http404
class User(AbstractBaseUser, PermissionsMixin):
public_id = models.UUIDField(db_index=True, unique=True, default=uuid.uuid4, editable=False)
username = models.CharField(db_index=True, max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField(db_index=True, unique=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) created = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def \_\_str\_\_(self): return f"{self.email}" @property def name(self): return f"{self.first_name} {self.last_name}"
The models module from Django provides
- field utilities
- model property
- __str__ method to return a string that can help us quickly identify a User object.
Let’s write UserManager so we can have methods to create a user and a superuser:
class UserManager(BaseUserManager):
def get_object_by_public_id(self, public_id):
try: instance = self.get(public_id=public_id) return instance except (ObjectDoesNotExist, ValueError, TypeError): return Http404 def create_user(self, username, email, password=None, **kwargs): """Create and return a `User` with an email, phone number, username and password.""" if username is None: raise TypeError('Users must have a username.') if email is None: raise TypeError('Users must have an email.') if password is None: raise TypeError('User must have an email.') user = self.model(username=username, email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password, **kwargs): """ Create and return a `User` with superuser (admin) permissions. """ if password is None: raise TypeError('Superusers must have a password.') if email is None: raise TypeError('Superusers must have an email.') if username is None: raise TypeError('Superusers must have an username.') user = self.create_user(username, email, password, **kwargs) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user
Before running the migrations (everytime a new app was added to the project)
we need to register the user application in INSTALLED_APPS in CoreRoot/settings.py.
goto /projectFolder/CoreRoot/settings.py
> add the new app: core.newapp
inside the new app folder in Apps.py:
###
from django.apps import AppConfig
class UserConfig(AppConfig):
default_auto_field = ‘django.db.models.BigAutoField’
name = ‘core.user’
label = ‘core_user’
###
Where name and name show how apps are nested
tell Django to use this User model for the authentication user model. In the settings.py file, add the following line:
goto /projectFolder/CoreRoot/settings.py
> at the end of the file add: AUTH_USER_MODEL = ‘core_user.User’