thaiall logomy background
จังโก้ หรือดีจังโก้ (Django)
my town
django จังโก้ (Django) คือ เฟรมเวิร์คภาษาไพทอน (Python Framework) ในแบบ MTV (Model-Template-View) แต่ยังสนับสนุน MVC (Model, Views, Controller) ช่วยในการพัฒนาระบบได้อย่างรวดเร็ว แทนการพัฒนาตามหลักโปรแกรมโครงสร้าง หรือหลักการโปรแกรมเชิงวัตถุ
ทำตาม your first Django app, part 1 และ part 2 ซึ่ง part 2 ทำให้ได้ระบบจัดการข้อมูล เชื่อมกับระบบฐานข้อมูล sqlite3 ซึ่งใช้ค่าปริยายที่ django framework เตรียมระบบมาให้ใช้งาน ด้วยการสร้างโปรเจค และแอปพลิเคชัน ผ่านคำสั่ง django-admin startproject testsite และ python manage.py startapp polls มีรายละเอียดที่ต้องดำเนินการมากมาย คล้าย laravel บน php ซึ่ง settings.py กำหนดให้ใช้ sqlite3 ที่มีมาในตัวโปรแกรม ไม่ได้เปลี่ยนไปใช้ mysql ส่วน templates ก็ใช้ DjangoTemplates ตามที่เซตมา
https://www.tutorialspoint.com/django/django_overview.htm
https://en.wikipedia.org/wiki/Django_(web_framework)
https://wikipopular.com/th/Django_web_framework
# python

```
https://www.python.org/downloads/
https://www.python.org/ftp/python/3.9.6/python-3.9.6-amd64.exe (25 MB)
1) Search , python  2) Start button, IDLE - window form 2) Start button, Python - command line* 4) Run, py 5) run, cmd, py
C:\> py
>>> exit() หรือ ctrl-break
C:\> nodepad myserver.py (210 bytes)
import os
from http.server import HTTPServer, CGIHTTPRequestHandler
os.chdir('.')
server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler)
server_object.serve_forever()
C:\> py myserver.py (Allow access)
http://localhost in chrome หรือ http://localhost/myserver.py in chrome
Ctrl-Break to stop server
```

---

# python cgi-bin

```
สร้าง folder cgi-bin ใน root directory
ใช้ notepad สร้างแฟ้ม hello.py ใน cgi-bin
print ("Content-Type: text/html\n\n")
print ("Hello World!")
เปิด localhost/cgi-bin/hello.py จะเห็นเฉพาะ Hello World!
ถ้าสร้างแฟ้ม hello.py ใน root directory แล้วเปิด จะเห็น source code
```

---

# python flask

```
ติดตั้ง Flask
C:\> py -m pip install Flask
C:\> notepad code1.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def Home():
   return "<h1>Hello</h1>"
if __name__ == '__main__':
 app.debug = True
 app.run(host='0.0.0.0', port=8000)
C:\> py code1.py 
 explorer http://172.50.0.7:8000/
 Ctrl-C to quit
https://www.borntodev.com/2020/02/19/ทำเว็บด้วย-python/
```

---

# python django

```
Django framework บน python
C:\> py -m pip install --upgrade pip
C:\> py -m pip install django
C:\> py -m pip uninstall django
C:\> py -m pip install -e django
C:\> cd C:\Users\LAB\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9
C:\> cd C:\Users\LAB\AppData\Local\Programs\Python\Python39
https://www.stanleyulili.com/django/how-to-install-django-on-windows/
C:\django> py -m venv venv
C:\django> venv\Scripts\activate
(venv) C:\Users\LAB\django>
(venv) C:\Users\LAB\django> pip install django
(venv) C:\Users\LAB\django> django-admin --version (3.2.5)
(venv) C:\Users\LAB\django> django-admin startproject testsite
(venv) C:\Users\LAB\django> cd testsite
(venv) C:\Users\LAB\django\testsite> dir
(venv) C:\Users\LAB\django\testsite> python manage.py runserver
explorer http://127.0.0.1:8000/
Ctrl-Break to quit
>>> import django
>>> django
<module 'django' from 'C:\\Users\\LAB\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\__init__.py'>
https://codeburst.io/%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%9E%E0%B8%B1%E0%B8%92%E0%B8%99%E0%B8%B2-web-application-%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2-python-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-django-framework-38ce132ac706
```

---

# python polls - part 01

```
https://docs.djangoproject.com/en/3.2/intro/tutorial01/
C:\Users\LAB\django> venv\Scripts\activate
(venv) C:\Users\LAB\django> django-admin startproject testsite
(venv) C:\Users\LAB\django> cd testsite
(venv) C:\Users\LAB\django\testsite> python manage.py runserver
Ctrl-Break to quit
(venv) C:\Users\LAB\django\testsite> python manage.py startapp polls
(venv) C:\Users\LAB\django\testsite\polls> cd polls
(venv) C:\Users\LAB\django\testsite\polls> notepad views.py
เดิม
from django.shortcuts import render
# Create your views here.
ใหม่
from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

(venv) C:\Users\LAB\django\testsite\polls> notepad urls.py (create file)
from django.urls import path
from . import views
urlpatterns = [
    path('', views.index, name='index'),
]

(venv) C:\Users\LAB\django\testsite\polls>  cd..
(venv) C:\Users\LAB\django\testsite> cd testsite  
(venv) C:\Users\LAB\django\testsite\testsite> notepad urls.py
เดิม
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]
ใหม่
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
(venv) C:\Users\LAB\django\testsite> python manage.py runserver

---

# python polls - part 02

```
https://docs.djangoproject.com/en/3.2/intro/tutorial02/
(venv) C:\Users\LAB\django\testsite\testsite> notepad settings.py (เปิดดูเฉย ๆ รายละเอียดเยอะ)
(venv) C:\Users\LAB\django\testsite\testsite> cd ..
(venv) C:\Users\LAB\django\testsite> python manage.py migrate
(venv) C:\Users\LAB\django\testsite\polls> notepad models.py
เดิม
from django.db import models
# Create your models here.
ใหม่
from django.db import models
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

(venv) C:\Users\LAB\django\testsite\polls> cd ../testsite
(venv) C:\Users\LAB\django\testsite\testsite> notepad settings.py
เดิม
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
ใหม่
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

(venv) C:\Users\LAB\django\testsite\testsite> cd ..
(venv) C:\Users\LAB\django\testsite> python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question
    - Create model Choice

(venv) C:\Users\LAB\django\testsite> python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "c
hoice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" bigin
t NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id
");
COMMIT;

(venv) C:\Users\LAB\django\testsite> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

(venv) C:\Users\LAB\django\testsite> python manage.py shell
from polls.models import Choice, Question
Question.objects.all()
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
q.question_text
q.pub_date
q.question_text = "What's up?"
q.save()
Question.objects.all()
# Ctrl-Break

(venv) C:\Users\LAB\django\testsite> cd polls
(venv) C:\Users\LAB\django\testsite\polls> notepad models.py
ปรับใหม่หลายเขตข้อมูล
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text
(venv) C:\Users\LAB\django\testsite\polls> cd ..
(venv) C:\Users\LAB\django\testsite> python manage.py shell
from polls.models import Choice, Question
Question.objects.all()
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith='What')
from django.utils import timezone
current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)
Question.objects.get(id=2)
Question.objects.get(pk=1)
q = Question.objects.get(pk=1)
q.was_published_recently()
q = Question.objects.get(pk=1)
q.choice_set.all()
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.question
q.choice_set.all()
q.choice_set.count()
Choice.objects.filter(question__pub_date__year=current_year)
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()

(venv) C:\Users\LAB\django\testsite> python manage.py createsuperuser
user : test password : test

(venv) C:\Users\LAB\django\testsite> python manage.py runserver
http://127.0.0.1:8000/admin/ (test : test)
---

# python function

```
C:\> nodepad input.py
def checkName(name):  
	checkName = input("Name :" + name + "?") 
	if checkName.lower() == "yes":    
		print("Hello,", name)  
	else:    
		print("no boy")
checkName("boy")
C:\> py input.py
```
rspsocial
Thaiall.com