owned this note
owned this note
Published
Linked with GitHub
---
title: Django Tutorial 1
tags: django, web
slideOptions:
transition: 'slide'
---
# Django Tutorial 1
### Speaker: Chih-Wei, Hsu

[About me](https://www.linkedin.com/in/kevin12686/)
---
# Frontend ?
# Backend ?
----
```sequence
User->Frontend: Read Article
Frontend-->Backend: Get Data
Note right of Frontend: Getting Data
Backend-->Frontend: Give Data
Frontend->User: Reading Article
```
----
## Getting Data ?

----

# Request Methods
* GET
* POST
* etc.
----
## GET
Arguments Passed with URL
<font color="SkyBlue">Dcard Search Function</font>
[https://www.dcard.tw/search<span><!-- .element: class="fragment highlight-red" -->?query=成功大學</span>](https://www.dcard.tw/search?query=成功大學)
----
## POST
Arguments Go with request
:warning:
<font color="#EAC117">Hided behind, not safe!</font>
---
# HTTP Status Code
----
| Code | Meanning |
|:----:|:---------------------:|
| 200 | Success |
| 3xx | Redirect |
| 400 | Bad Request |
| 403 | Forbidden |
| 404 | Not Found |
| 405 | Method Not Allowed |
| 500 | Internal Server Error |
[Details](https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Status)
----
2xx :+1:
4xx :no_entry:
5xx :middle_finger:
---
# Prepare
[Python 3](https://www.python.org/downloads/)
----
## Work With Github
Create a new repository
----
## Create Virtual Environment
`python -m venv <name>`
----
## Activate
`cd venv/Scripts`
`activate`
----
## Deactivate
`deactivate`
----
## Install Django
`pip install django`
----
## Requirements
`pip freeze > requirements.txt`
----
## Install Requirements
`pip install -r requirements.txt`
----
## Add .gitignore
\_\_pycache\_\_/
venv/
migrations/
*.sqlite3
----
## Create project
`django-admin startproject <name>`
----
```
django_tutorial
│ .gitignore
│ requirements.txt
├───backend
│ │ manage.py
│ └───backend
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
└───venv
```
----
## Run
`python manage.py runserver`
```shell
Performing system checks...
System check identified no issues (0 silenced).
August 10, 2020 - 10:24:48
Django version 3.1, using settings 'backend.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
```
----
[http://127.0.0.1:8000/](http://127.0.0.1:8000/)

----
## Git push

[Check Point 1](https://github.com/kevin12686/django_tutorial/tree/94ae7d7970de8f553613e0ac74bb217ee2a61d11)
---
# Django
[More](https://www.djangoproject.com/)
----

[Source](https://djangogirlstaipei.gitbooks.io/django-girls-taipei-tutorial/content/django/introduction.html)
---
# Simple Blog
----
## settings.py
Configuration of the Django installation
### Modify
```python
LANGUAGE_CODE = 'zh-Hant' # Modify
TIME_ZONE = 'Asia/Taipei' # Modify
```
[Details](https://docs.djangoproject.com/en/3.1/topics/settings/)
----
## Create app
The name of this example will be 'blog'
`python manage.py startapp <name>`
----
## blog/views.py
### Add
```python
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the blog index.")
```
----
## backend/urls.py
### Modify
```python
from django.urls import path, include
```
### Add
```python
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')), # Add
]
```
----
## blog/urls.py
### Add
```python
from django.urls import path
from .views import index
urlpatterns = [
path('', index, name='Index'),
]
```
----
[http://127.0.0.1:8000/](http://127.0.0.1:8000/)

----
## Git push

[Check Point 2](https://github.com/kevin12686/django_tutorial/tree/ae4cd292584801bd0b993ac3d08b394ef5edd500)
---
# Models
What fields are the blog needed
----
* Title
* Content
* EditTime
----
## Data Type
## &
## Restriction
----
* Title
* Unique and less than 50 words
* Content
* Unlimit length
* EditTime
* Date and Time
----
## blog/models.py
### Add
```python
class Blog(models.Model):
title = models.CharField(unique=True, max_length=50, verbose_name='Title')
content = models.TextField(verbose_name='Content')
editTime = models.DateTimeField(auto_now=True, verbose_name='Edit Time')
```
[More about fields](https://docs.djangoproject.com/en/3.1/ref/models/fields/)
----
## backend/settings.py
### Add
```python
INSTALLED_APPS = [
'blog.apps.BlogConfig', # Add
...
]
```
----
## Make migrations
`python manage.py makemigrations <app>`
----
```shell
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Blog
```
----
## Migrate
`python manage.py migrate`
----
```shell
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
```
---
# Django Admin
Provide a easy way to manage contents
----
## blog/admin.py
### Add
```python
from django.contrib import admin
from .models import Blog # Add
admin.site.register(Blog) # Add
```
----
[http://127.0.0.1:8000/admin/](http://127.0.0.1:8000/admin/)

----
## Create Superuser
`python manage.py createsuperuser`
----
```shell
Username: admin
Email address:
Password: ****
Password (again): ****
Superuser created successfully.
```
----
## Login

----
## Git push

[Check Point 3](https://github.com/kevin12686/django_tutorial/tree/55ba9bb3fdfdfd0499bd5e6c0053aa39c5aa8839)
---
# Exercise
Create a website for selling products
* Require model
* Product
* Fields
* Name
* Description
* Quantity
* etc.
---
# Listing
----
## Templates
Create a folder 'templates' under 'blog'
----
## backend/settings.py
### Modify
```python
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Path.joinpath(BASE_DIR, 'blog', 'templates'), ], # Modify
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
```
----
## blog/views.py
### Modify
```python
from django.shortcuts import render # Add
from .models import Blog # Add
def index(request):
blogs = Blog.objects.all() # Modify
return render(request, 'index.html', {'blogs': blogs}) # Modify
```
----
## bolg/templates/index.html
### Add
```htmlembedded
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<ul>
{% for blog in blogs %}
<li>{{ blog.title }}</li>
{% endfor %}
</ul>
</body>
</html>
```
----
[http://127.0.0.1:8000/](http://127.0.0.1:8000/)

----
## Git push

[Check Point 4](https://github.com/kevin12686/django_tutorial/tree/2137085da2f6b234ca2db7917a77885cec12d522)
---
# RESTful API
Each request methods have their own meaning
----
| Method | Meaning |
|:------:|:-------:|
| GET | Read |
| POST | Create |
| PUT | Update |
| DELETE | Delete |
----
# Json
Javascript Object Notation
----
`{}` descripts an object with key and value
`[]` represents as an array
---
# Rest Framework
[More](https://www.django-rest-framework.org/)
----
## Install
`pip install djangorestframework`
----
## Update requiremnets
`pip freeze > requirements.txt`
----
## backend/settings.py
### Add
```python
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
'rest_framework', # Add
]
```
----
## blog/serializers.py
### Add
```python
from rest_framework.serializers import ModelSerializer
from .models import Blog
class BlogSerializer(ModelSerializer):
class Meta:
model = Blog
fields = '__all__'
```
----
## blog/views.py
### Add
```python
from rest_framework.viewsets import ModelViewSet
from .serializers import BlogSerializer
class BlogViewSet(ModelViewSet):
serializer_class = BlogSerializer
queryset = Blog.objects.all()
```
----
## blog/urls.py
### Modify
```python
from django.urls import path, include # Modify
from rest_framework.routers import DefaultRouter # Add
from .views import index, BlogViewSet # Modify
router = DefaultRouter() # Add
router.register('blog', BlogViewSet) # Add
urlpatterns = [
path('', index, name='Index'),
path('api/', include(router.urls)), # Add
]
```
----
[http://127.0.0.1:8000/api/](http://127.0.0.1:8000/api/)

----
[http://127.0.0.1:8000/api/blog/](http://127.0.0.1:8000/api/blog/)

----
[http://127.0.0.1:8000/api/blog/?format=json](http://127.0.0.1:8000/api/blog/?format=json)
```json
[
{
"id":1,
"title":"blog1",
"content":"hello this is blog 1",
"editTime":"2020-08-11T09:35:50.677858+08:00"
},
{
"id":2,
"title":"blog 2",
"content":"hello this is blog 2",
"editTime":"2020-08-11T09:36:01.424723+08:00"
},
{
"id":3,
"title":"blog 3",
"content":"hello this is blog 3",
"editTime":"2020-08-11T09:36:11.285941+08:00"
}
]
```
----
## Git push

[Check Point 5](https://github.com/kevin12686/django_tutorial/tree/c56acc0302eae507ad5176d1283c969aaef81d80)
---
# Exercise
List products with a page and an api
Give list page some styles
---

[Github](https://github.com/kevin12686/django_tutorial)
---
<!-- .slide: data-background="https://i.imgur.com/VrcGp6z.png" -->