Django Introduction

  • 如何從頭建立一個 Django 專案
  • 使用 ORM 連結 postgresql 資料庫

Youtube 影片

開始一個專案 (Project)

$mkdir python-project
$virtualenv ENV 
$pip install django
$django-admin startproject djangoproject
  • Vagrant client 需要修改 settings.py
ALLOWED_HOSTS = ["192.28.128.102"]  
  • 執行
$python manage.py runserver 0:4300

建立一個 app

  • 一個專案可以有多個 app
  • 建立一個 app
$python manage.py startapp blog
  • 產生檔案如下
blog
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│   └── __init__.py
├── models.py
├── tests.py
└── views.py

修改 views.py

from django.http import HttpResponse

def index(request):
		return HttpResponse('Hello from Posts')

建立一個 urls.py

from django.urls import path

from . import views

urlpatterns = [
		path('', views.index, name='index'),
]

修改專案的 urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
		path('', include('blog.urls')),
		path('blog/', include('blog.urls')),
		path('admin/', admin.site.urls),
]

  • 執行
$python manage.py runserver

設定 Database

  • 使用 Postgresql 9.6
  • 須先安裝 pip install psycopg2-binary
  • 修改 settings.py
DATABASES = {
		'default': {
				'ENGINE': 'django.db.backends.postgresql_psycopg2',
				'NAME': 'myproject',
				'USER': 'jerry',
				'PASSWORD': 'Jerry001',
				'HOST': 'localhost',
				'PORT': '',
		}
}
  • psql > CREATE DABASE blog;
  • python manage.py migrate 來建立 Dabase
Operations to perform:
  Apply all migrations: admin, auth, 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 sessions.0001_initial... OK

產生的 table

blog=> \dt
                      relation 清單
 架構模式 |            名稱            | 型別  | 擁有者  
----------+----------------------------+-------+---------
 public   | auth_group                 | table | vagrant
 public   | auth_group_permissions     | table | vagrant
 public   | auth_permission            | table | vagrant
 public   | auth_user                  | table | vagrant
 public   | auth_user_groups           | table | vagrant
 public   | auth_user_user_permissions | table | vagrant
 public   | django_admin_log           | table | vagrant
 public   | django_content_type        | table | vagrant
 public   | django_migrations          | table | vagrant
 public   | django_session             | table | vagrant
(10 筆資料列)

建立模型 (Models) models.py

from django.db import models
from datetime import datetime

# Create your models here.

class Posts(models.Model):
		title = models.CharField(max_length=200)
		body = models.TextField()
		created_at = models.DateTimeField(default=datetime.now, blank=True)

將 app 包含入專案

INSTALLED_APPS = [
		'blog',
		'django.contrib.admin',
		'django.contrib.auth',
		'django.contrib.contenttypes',
		'django.contrib.sessions',
		'django.contrib.messages',
		'django.contrib.staticfiles',
]

建立 migrations, 執行 migrate 來建立 Model

  • python manage.py makemigrations blog
  • 產生 migrations py
Migrations for 'blog':
	blog/migrations/0001_initial.py
		- Create model Blog
  • 執行 migrate

$python manage.py migrate blog

建立一個系統的 Admin 使用者

  • $python manage.py createsuperuser
Username (leave blank to use 'vagrant'): Jerry
Email address: [email protected]
Password: 
Password (again): 
Superuser created successfully.
  • 重新跑 server python manage.py runserver 0:4300

進入 localhost:4300/admin

未命名_2018-08-28_17-37-01.png

登入後的畫面

未命名_2018-08-28_17-39-09.png

讓 Blog 代入 administration 畫面

  • 修改 admin.py
from django.contrib import admin

# Register your model blog 下增加ere.
from .models import Blog

admin.site.register(Blog)

產生新的畫面

未命名_2018-08-28_17-43-15.png

加入一個新的 post

未命名_2018-08-28_17-45-02.png

加入後畫面

未命名_2018-08-28_17-46-50.png

Blog Object(1) 不是很清楚的名字

  • 修改 models.py 加入
def __str__(self):
	return self.title

修改後加入另一個 po blog 下增加的畫面

未命名_2018-08-28_21-05-21.png

開始修改 Homepage

  • 建立 templates/blog/index.html
<html>
  <head>
<title>Onion Studio Blog</title>
</head>
<body>
<h1>Onion Studio Blog</h1>
<h3>List of Blog Posts</h3>
<ul>
	{% for post in posts %}
  <li> <a href=/blog/details/{{post.id}}>{{post.title}}</a></li>
	{% endfor %}
</ul>
</body>
</html>

修改 views.py

from django.shortcuts import render
#from django.http import HttpResponse

# Create your views here.
from .models import Blog

posts = Blog.objects.all()[:10]

context = {
		'title': 'Latest Posts',
		'posts': posts
}

def index(request):
		#    return HttpResponse('Hello from Posts')
		return render(request, 'posts/index.html', context)

修改後畫面

未命名_2018-08-28_20-13-43.png

增加 post detail

  • blog 下增加 urls.py
from django.urls import path
from . import views

urlpatterns = [
		path('', views.index, name='index'),
		path('details/<int:id>', views.details,  name='detail')
]

修改 views.py 增加

#...
def details(request, id):
		print(id)
		post = Posts.objects.get(id=id)
		context = {
				'post': post
		}

		return render(request, 'blog/details.html', context)

增加 details.html

<html>
  <head>
<title>Onion Studio Blog</title>
</head>
<body>
<h1>Onion Studio Blog</h1>
<h3> {{post.title}} </h3>
<p>{{post.body}}</p>
<br/>
{{post.created_at}}
</body>
</html>

完成之畫面

未命名_2018-08-28_20-51-58.png

Notice: compact(): Undefined variable: limits in /var/www/html/wp-includes/class-wp-comment-query.php on line 853 Notice: compact(): Undefined variable: groupby in /var/www/html/wp-includes/class-wp-comment-query.php on line 853

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *