
สร้างโปรเจ็ค Django
$ django-admin startproject django_starter //สร้งโปรเจ็ค Django
$ py manage.py startapp website_management //สร้างโปรเจ็คย่อยในโฟลเดอร์$ py manage.py shell>>> from blog.models import Post
>>> Post.objects.all()

จะได้ไฟล์
__init__.py ไฟล์วางที่เอาไว้บอกข้อมูลเบื้องต้น
settings.py ตั้งค่าฐานข้อมูล path folder
urls.py ตั้งค่า url สำหรับเว็บไซต์
wsgi.py ตั้งค่าในการรันโปรเจ็ค Web Server Gateway Interface (WSGI)
$ py manage.py runserver 0.0.0.0:8000 //รันเว็บไซต์ port 8000
Template
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from website_management.models import Category, Websitedef index(request):
header_str = 'Hello, Python variable'
context = {
'var1' : header_str,
'cat_num': len(Category.objects.all()),
'web_num': len(Website.objects.all())
}
return render(request, 'index.html', context)
โดยสร้าง Folder templates ขึ้นมาแล้วใส่ไฟล์ index.html
StaticFile
$ python manage.py collectstatic*หลังจากรันคำสั่งนี้ static Folder จะไปอยู่ path เดียวกับ setiings.py
{% load static %}
<link rel="stylesheet" href="{% static "style.css" %}">
<img src="{% static 'background.png' %}"/>
server static locally
py manage.py runserver --insecure
WhiteNoise
ใช้สำหรับ static ไฟล์แบบ local
https://whitenoise.evans.io/en/stable/django.html
pip install whitenoise
ใส่ whitenoise ใน settings.py
MIDDLEWARE =["whitenoise.middleware.WhiteNoiseMiddleware",]
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
Database
ถ้าสร้าง models แล้วเราสามารถ Migration File จาก Model ที่มีไปสู่ database ได้
$ py manage.py makemigrations //สร้างไฟล์สำหรับ migration
$ py manage.py makemigrations websites //สร้างไฟล์สำหรับ migration ย่อย$ py manage.py migrate //สั่งให้สร้างฐานข้อมูลจาก migrate
$ py manage.py migrate websites //สั่งให้สร้างฐานข้อมูลจาก migrate ย่อย
Models
Admin
$ py manage.py createsuperuser //create super user
Shell
$ py manage.py shell //สามารถเข้าใช้งานฐานข้อมูลได้ด้วย shell>>> from website_management.models import Category, Website
>>> Category.objects.all()