Django Notes
- Start the Django project (foo as the project name and bar as the app name)
- The admin site
- The Django shell (Control-d to exit)
- Making pages
- References
Start the Django project (foo as the project name and bar as the app name)
-
Create a virtual environment (where we can install packages and isolate them from all other packages): (venv is the virtual environment module.)
1
python3 -m venv foo
-
Activate the virtual environment: (Packages inside will be available only when the environment is active.) (use
deactivate
to deactivate.)1
source foo/bin/activate
-
Install Django (Note: use
python
andpip
instead ofpython3
orpip3
) in the virtual environment.1
pip install django
-
Start the project. (The dot at the end creates the project with a directory structure, i.e. with
__init__.py
,settings.py
,urls.py
, andwsgi.py
(web server gateway interface.))1
django-admin startproject foo .
-
Create the database (SQLite): (Run the command anytime we modify the database.)
1
python manage.py migrate
-
Start and view the project:
1
python manage.py runserver
-
A Django project is a group of individual apps that work together. Let’s start an app: (creating the following in the bar folder:
__init__.py
,admin.py
,apps.py
,migrations
,models.py
,test.py
, andview.py
.)1
python manage.py startapp bar
-
Code-wise, a model is just a class. An example model:
1 2 3 4 5 6 7 8 9 10 11
from django.db import models # Create your models here. class Topic(models.Model): """The class that manages the topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """The string representation of the model.""" return self.text
-
Activate the models:
-
Add the apps to
INSTALLED_APPS
insettings.py
;1 2 3 4 5 6 7 8 9 10 11 12
INSTALLED_APPS = [ # My apps 'bar', # Default django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
-
Migrate:
1 2
python manage.py makemigrations bar python manage.py migrate
-
The admin site
-
Add a superuser: (Django only stores the hash of the password)
1
python manage.py createsuperuser
-
Register the model with the admin site. Example
admin.py
:1 2 3 4 5 6 7 8
from django.contrib import admin # Register your models here. from .models import Topic, Entry # . means looking for the file in the same directory as admin.py admin.site.register(Topic) admin.site.register(Entry)
The Django shell (Control-d to exit)
-
Example:
1 2 3
python manage.py shell >>> from bar.models import Topic >>> Topic.objects.all() # returns a queryset
Making pages
-
Defining URLs:
-
Include the URLs in foo/urls.py:
1 2 3 4 5 6 7
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('bar.urls')), ]
-
Create a new bar/urls.py file and add the following:
1 2 3 4 5 6 7 8 9
from django.urls import path from . import views app_name = 'bar' urlpatterns = [ # a list of individual pages that can be requested. # Homepage path('', views.index, name='index'), # '' means the base URL; call the index() function in views.py ]
-
-
Writing views:
1 2 3 4 5
from django.shortcuts import render def index(request): """The homepage.""" return render(request, 'bar/index.html')
-
Writing templates:
-
Make the directory bar/templates/bar
-
Write the file index.html:
1 2 3
<p>Learning Log</p> <p>Learning Log helps you keep track of your learning, for any topic you're learning about.</p>
-
If we see the error:
ModuleNotFoundError: No module named 'learning_logs.urls'
, just CTRL-C and rerun the server bypython manage.py runserver
. -
Template inheritance:
-
Make a base.html file and include it on every page: (template tag:{percent percent}; bar is the namespace defined in bar/urls.py app_name) (in reality, use % instead of percent! here is just for avoiding the markdown error.)
1 2 3 4 5
<p> <a href="{percent url 'bar:index' percent}">Foo</a> </p> {percent block content percent}{percent endblock content percent}
-
Inherit the base.html: (index.html)
1 2 3 4 5
{percent extends "bar/base.html" percent} {percent block content percent} <p>Learning Log helps you become a better learner by keeping track of the topic you're learning.</p> {percent endblock content percent}
-
-