djangogirls/django-girls.md

219 lines
5.0 KiB
Markdown
Raw Permalink Normal View History

2020-10-19 13:46:15 +11:00
# django girls blog
Target: create a blog using django.
## 01 Your first Django project!
### 1.1 Create Django project
* Command to start Django project:
```
$ django-admin startproject mysite.
```
Generating following dir structure:
```
djangogirls
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── myvenv
│ └── ...
└── requirements.txt
```
where:
* `setting.py`L: helps with management of the site.
* contains configuration of the website
* `urls.py`: contains a list of patterns used by `urlresolve`
### 1.2 Change settings of django website
Edit `mysite/settings.py`:
1. Change timezone: `TIME_ZONE=Australia/Canberra'
2. Change language: `LANGUAGE_CODE = 'en-us'
3. Add a path for static files (e.g. CSS and static files): `STATIC_ROOT = os.path.join(BASE_DIR, 'static')`
4. Add allowed host site: `ALLOWED_HOST = ['127.0.0.1', '.amazonaws.com']` for using cloud9
### 1.3 Set up a database
Django support multiple databases, to store data. `sqlite3` is the default one, which is already set up as shown in `mysite/settings.py`:
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
```
After confirming database settings, migrate the project `python manage.py migrate`
### 1.4 Starting the web server
```
python manage.py runserver
```
## 2. Django models
2020-10-19 15:30:16 +11:00
Target: create objects that store all posts in the blog.
### 2.1 Objects
In OOP, object containing member data and member function. We try to model the blog's objects as well.
Q:
* How will we model blog posts?
* What is a blog post?
* What properties should it have?
A:
* Blog posts need
* text with content and title
* author
* date of created/published
Object's data can be shown as below:
```
Post
-------
title
text
author
created_date
published_date
```
Blog object's method:
* `publish`
### 2.2 Django model
A model in Django is a special kind of obj, saved in `database`. Analogy: A model in database is like a spreadsheet with columns (fields) and rows (data).
#### 2.2.1 Creating and app
For organization, we create a separate app inside the web project, which contains logic and model.
```
$ python manage.py startapp blog
```
It created a dir called `/blog` that containing scripts:
```
djangogirls
├── blog
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
|...
```
After creating app, `mysite/settings.py` should be changed to let Django notice the app.
```python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# first party
'blog.apps.BlogConfig',
]
```
* `blog.apps.BlogConfig` is the class that in `blog/apps.py` script
#### 2.2.2 Creating a blog post model
For each app, there is a `models.py` that contains models (obj), modify it to contain post obj
```python
from django.db import models
from django.conf import settings
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
```
Explaining Post class:
* `models.Model` the base class the Post class inherit from. It means `Post` is a Django Model, so Django can save it in database
* Properties are defined as Django's model data type:
* `models.CharField`: A Django model class that define text with limited number of char
* `models.TextField`: long text w/o limit
* Check django models->fields->field-types
#### 2.2.3 Create tables for models in database
After creating new model, we need to add it into database:
1. Let Django know there is change: `python manage.py makemigrations blog`
1. So, Django will prepare a migration file
2020-10-19 15:41:33 +11:00
2. After prepared migration file `blog/migrations/0001_initial.py`, apply it to database: `python manage.py migrate blog`
## 3. Django admin
To adding/editing posts, need use Django admin
### 3.1 Add Post models into admin site
Edit `blog/admin.py`
```python
from django.contrib import admin
from .models import Post
admin.site.register(Post)
```
### 3.2 Add superuser to get access
```
python manage.py createsuperuser
```
### 3.3 Add/Edit post in admin site
Start webserver `python manage.py runserver` then go to http://127.0.0.1/admin
In the post, we can find it has multiple attributes/members including:
* `author`
* `Title`
* `Text`
* `Created date`
* `Published date`
They are all forms that we created in Post model
## 4. Deploy (Omit)