# Django Starter Notes --- ## Environment --- 1. Make sure pip is installed 2. Create a environments folder outside of where any project will live 3. In terminal ``` cd environments python -m venv myEnv (myEnv is just the name your are giving the universal environment) cd ../ ``` 4. Now activate the environment ``` Windows: source environments/myEnv/Scripts/activate Mac: source environments/myEnv/bin/activate ``` - If you know the path relative to your current terminal location you can activate your environment from any where 5. To Terminate the environment - can also be done from anywhere ``` deactivate ``` ### Install pip packages needed for the application Typical packages - django - bcrypt - pillow (allowes for uploads) - django-cors-headers (cross site apps) - django-environ (hiding of secret and api keys) - djangorestframework - fastapi - ipython (better shell environment) - requests (goes with api) - mysql-connector-python (allows you to use mysql vs django defalut of db3) - mysqlclient (another option to connect via mysql) ``` pip install django bcrypt ``` - You can install packages from anywhere in the system as long as it is activated - pip list will display all packages installed ### Create requirements.txt - This file allows for easy package installation for other users ``` pip freeze > requirements.txt ``` - Running this will create the file where ever you are in the terminal recommended to run inside root of project folder ### Updating your local ENV from requirements.txt - Run the following command ``` pip install -r requirements.txt ``` ## Starting / Creating base Django application --- 1. At root of repository or where the project will live with environment running and at least django pip installed ``` django-admin startproject projectName ``` 2. Once this is created you can make the app side (this is where all the work gets done) ``` python manage.py startapp appName ``` 3. You can create more than 1 app to help keep code more organized 4. Recommended to name the app's userApp, storeApp things like that to ensure others understand ## Initial server test Feel free to test django runs at this point ``` python manage.py runserver ``` open up 127.0.0.1:8000 and you should see the rocket ## Basic Prep before coding - This will include editing in the main project folder and connecting the apps as well as some basic app set up for organization. - Once this basic prep is started you need to finish it before running application again ### Settings.py (in project folder) ```python # Add to top where other imports are import os from environ import Env env = Env() env.read_env() # BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Take current key and place in .env file setting it equal to KEY (be sure to share the key unless using mysql for backend) SECRET_KEY = 'KEY' # If planning to deploy recommended to add the false commented out so it is there already DEBUG = True # DEBUG = False # If using multiple stacks or api framework add these tothe allowed hosts including any for like react ALLOWED_HOSTS = ['localhost:8000','127.0.0.1:8000','127.0.0.1'] # needed if using as api at all CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', 'http://127.0.0.1:8000', 'http://127.0.0.1:5500' ] CORS_ALLOW_ALL_ORIGINS = True # Add apps to this like the userApp below and also add the other 2 lines if using api INSTALLED_APPS = [ 'coreApp.apps.CoreappConfig' 'userApp.apps.UserappConfig', 'corsheaders', 'rest_framework', ] # If api add this line to begining of middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] # In Templates edit the following line as follows 'DIRS': [os.path.join(BASE_DIR,'templates')], # Add to bottom or edit STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' # This is only needed if having uploads MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ``` Seems like a lot I know but trust me makes it better If using mysql comment out the current database section and use one of the following - Recommend if multiple folks using this have different mysql passwords have extra password lines and just comment out wrong one for your system ```python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbName', 'USER': 'root', 'PASSWORD': 'rootroot, 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, } } DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'dbName', 'USER': 'root', 'PASSWORD': 'rootroot', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, } } ``` - Thats is for settings.py - Bonus if you want to send emails add the following to the bottom host password goes in env file (you will need to follow some steps to get a alternate password for gmail) - ```python EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = HOST_PASSWORD ``` ### urls.py (in project folder) - Part of this will be present in the file already we will just be adding to it and editing a little ```python from django.contrib import admin from django.urls import path, include from userApp import views as app_views from coreApp import views as app_views # pull in any other apps you made as well from django.contrib.auth import views as auth_views urlpatterns = [ path('', include('coreApp.urls')), path('user/', include('userApp.urls')), # add other apps here as well with their own starting url path('admin/', admin.site.urls), ] ``` - Project folder edits are now done from here it is the same process for each app folder ### Make the following folders - templates (contains html files) - static (only needs to be in 1 app folder) - views (we are going to delete the views.py file and use this instead) - templatetags (if you plan to create custom jinja) #### Optional folders to make in main app folder - config (to contain any extra api keys or hidden things) - utils (to contian custom functions like the email funcitons) ### Create the following files #### urls.py (root of app folder) - This will contain all your routes for the app (specifically for this app folder) - These are example routes for the coreApp where on the project app urls.py you have it set to '/' ```python= from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static # All urls are at base / urlpatterns = [ path('', views.index), # path('about/', views.about), # path('contact/', views.contact), # path('logReg/', views.logReg), # path('logout/', views.logout), # # Admin Routes # path('theAdmin/', views.theAdmin), # the above route is if you want a custom admin pannel outside of the django default admin.. can't used admin ] # This goes on any app urls.py file that has any routes that might talk to something uploaded if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` #### In views folder - __init__.py ```python= from .root import * # These are for seperating your view functions each file will get added here like the above line ``` - root.py (view file where your functions will go) - add at least the following before turning on app ```python= from django.shortcuts import render, redirect from django.contrib import messages # you will import models and any other referanced files here as well def index(request): return redirect('/admin') # This will at least allow you to get the app up and running it will just redirect you back to the default django admin page. ``` - If you have more than 1 app folder make sure you don't repeat any function names At this point you can turn the app back on and it should load to the django admin login page You will see warnings that migrations need to be run at this point. No worries If you are using mysql make sure you have the base database created. Just need to create the database no tables