2019年11月3日 星期日

[ Django ] 影片網站資料庫及後台管理(七) - 資料新增並驗證

本篇文章動手實作新增第四筆影片資料(如下圖),並使用驗證表單。


1.撰寫post2.html

2.新增路徑urls.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""youtobeproj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from youtobeapp.views import home, post, postform, post2

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),
    path('index/', home),
    path('post/', post),
    path('postform/', postform),
    path('post2/', post2),
]

3.在views.py上新增post2函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from django.shortcuts import render, redirect
from youtobeapp.models import video
from youtobeapp.form import PostForm

# Create your views here.

def home(request):
    try:
        videos = video.objects.all()
    except:
        print("沒有任何資料")
    return render(request, 'index.html', locals())
    
def post(request):
    if request.method == "POST":
        name = request.POST["videoname"]
        width = int(request.POST["videowidth"])
        height = int(request.POST["videoheight"])
        src = request.POST["videosrc"]
        v = video.objects.create(name=name, width=width, height=height, src=src)
        v.save
        return redirect('/index/')
    return render(request, 'post.html', locals())
        
def postform(request):
    postform = PostForm()
    return render(request, "postform.html", locals())
    
def post2(request):
    if request.method == "POST":
        postform = PostForm(request.POST)
        if postform.is_valid():
            name = postform.cleaned_data["name"]
            width = int(postform.cleaned_data["width"])
            height = int(postform.cleaned_data["height"])
            src = postform.cleaned_data["src"]
            v = video.objects.create(name=name, width=width, height=height, src=src)
            v.save
            return redirect('/index/')
        else:
            print("證驗有誤")
    else:
        postform = PostForm()
    return render(request, 'post2.html', locals())

4.執行127.0.0.1:8000/post2,隨意輸入資料

5.輸入正確資料

6.執行結果

上一篇文章:影片網站資料庫及後台管理(六) - 表單模型化
下一篇文章:影片網站資料庫及後台管理(八) - 刪除資料

[ Django ] 影片網站資料庫及後台管理(六) - 表單模型化

輸入資料需要驗證,若未驗證容易引起不可遇期的問題發生。本篇文章在於使用Python程式,設計驗證表單。

1.增加驗證表單程式form.py

1
2
3
4
5
6
from django import forms
class PostForm(forms.Form):
    name = forms.CharField(max_length=50, initial='')
    width = forms.IntegerField(max_value=1280, min_value=640)
    height = forms.IntegerField(max_value=1280, min_value=640)
    src = forms.CharField(max_length=50, initial='')

2.在views.py上增加postform函式。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.shortcuts import render, redirect
from youtobeapp.models import video
from youtobeapp.form import PostForm

# Create your views here.

def home(request):
    try:
        videos = video.objects.all()
    except:
        print("沒有任何資料")
    return render(request, 'index.html', locals())
    
def post(request):
    if request.method == "POST":
        name = request.POST["videoname"]
        width = int(request.POST["videowidth"])
        height = int(request.POST["videoheight"])
        src = request.POST["videosrc"]
        v = video.objects.create(name=name, width=width, height=height, src=src)
        v.save
        return redirect('/index/')
    return render(request, 'post.html', locals())
        
def postform(request):
    postform = PostForm()
    return render(request, "postform.html", locals())

3.增加路徑urls.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""youtobeproj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from youtobeapp.views import home, post, postform

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),
    path('index/', home),
    path('post/', post),
    path('postform/', postform),
]

4.製作一個驗證表單form.html
5.記得使用python manage.py runserver啟動,並使用127.0.0.1:8000/postform來查看結果

6.在上圖的執行畫面中,按下右鍵選擇查看原始碼,就能瞭解本篇文章中,要表達如何用Python來設計HTML表單上的驗證功能。

上一篇文章:影片網站資料庫及後台管理(五) - 新增一筆資料
下一篇文章:影片網站資料庫及後台管理(七) - 資料新增並驗證

2019年11月2日 星期六

[ Django ] 影片網站資料庫及後台管理(五) - 新增一筆資料

1.在urls.py增加路徑

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""youtobeproj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from youtobeapp.views import home, post

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),
    path('index/', home),
    path('post/', post)
]

2.在views.py新增post函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.shortcuts import render, redirect
from youtobeapp.models import video

# Create your views here.

def home(request):
    try:
        videos = video.objects.all()
    except:
        print("沒有任何資料")
    return render(request, 'index.html', locals())
    
def post(request):
    if request.method == "POST":
        name = request.POST["videoname"]
        width = int(request.POST["videowidth"])
        height = int(request.POST["videoheight"])
        src = request.POST["videosrc"]
        v = video.objects.create(name=name, width=width, height=height, src=src)
        v.save
        return redirect('/index/')
    return render(request, 'post.html', locals())
        

3.新增一個post.html程式,儲存在templates目錄下。
4.啟動網站127.0.0.1:8000/post
5.執行結果,可以看到有3支影片

上一篇文章:影片網站資料庫及後台管理(四) - 讀取所有資料
下一篇文章:影片網站資料庫及後台管理(六) - 表單模型化

[ Django ] 影片網站資料庫及後台管理(四) - 讀取所有資料

1.修改views.py程式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.shortcuts import render
from youtobeapp.models import video

# Create your views here.

def home(request):
    try:
        videos = video.objects.all()
    except:
        print("沒有任何資料")
    return render(request, 'index.html', locals())

2.修改index.html


3.增加另一筆資料

4.執行結果

上一篇文章:影片網站資料庫及後台管理(三) - 建立資料庫
下一篇文章:影片網站資料庫及後台管理(五) - 新增一筆資料

[ Django ] 影片網站資料庫及後台管理(三) - 建立資料庫

1.開啟models.py,建立資料庫

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.db import models

# Create your models here.

class video(models.Model):
    name = models.CharField(max_length=50, null=False)
    width = models.IntegerField(default = 1280)
    height = models.IntegerField(default = 720)
    src = models.CharField(max_length=50, null=False)
    
    def _str_(self):
        return self.name    
    

2.開啟admin.py撰寫註冊video資料庫到後台管理

1
2
3
4
5
6
from django.contrib import admin
from youtobeapp.models import video

# Register your models here.

admin.site.register(video)


2.記得要執行下列指令,建立帳號:demo,密碼:1234
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

3.進入後台

4.建立第一筆資料


5.編輯views.py取得一筆資料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.shortcuts import render
from youtobeapp.models import video

# Create your views here.

def home(request):
    try:
        v = video.objects.get(name="Django")
        width=v.width
        height=v.height
        src = v.src
    except:
        print("沒找到")
        width=1280
        height=720
        src = 'W40mDCqWyYo'     
    return render(request, 'index.html', locals())

6.執行結果

上一篇文章:影片網站資料庫及後台管理(二) - 視圖和樣版
下一篇文章:影片網站資料庫及後台管理(四) - 讀取所有資料

[ Django ] 影片網站資料庫及後台管理(二) - 視圖和樣版



影片嵌入程式碼是採用iframe的標籤,其主要的參數有width, height, src等。

1.將index.html中重要的參數變數,{{width}}、{{height}}、{{src}}。

2.修改views.py程式

from django.shortcuts import render

# Create your views here.

def home(request):
    width=1280
    height=720
    src = 'W40mDCqWyYo'
    return render(request, 'index.html', locals())

3.啟動網站查看結果

上一篇文章:影片網站資料庫及後台管理(一) - 建立網站專案
下一篇文章:影片網站資料庫及後台管理(三) - 建立資料庫

[ Django ] 影片網站資料庫及後台管理(一) - 建立網站專案

今天助教跟敏哥分享很實用的編輯工具,Notepad++,歡迎大家下載:https://notepad-plus-plus.org/downloads/
1.建置虛擬環境
mkvirtualenv youtobe
pip install django
django-admin startproject youtobeproj
cd youtobeproj
python manage.py startapp youtobeapp

上圖中發現敏哥在實作過程中,還是會漏掉一些字,造成找不到檔案或目錄(No such file or directory)。

2.設定youtobeapp以及templates的目錄。


"""
Django settings for youtobeproj project.

Generated by 'django-admin startproject' using Django 2.2.6.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'geg*jh5ejci37xw3rp*eb_=^=)0uz#20*s((bwm%f^9z*8&#&2'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'youtobeproj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'youtobeproj.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'zh-Hant'

TIME_ZONE = 'Asia/Taipei'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
  os.path.join(BASE_DIR, 'static'),
 ]

3.修改urls.py程式

"""youtobeproj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from youtobeapp.views import home

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

4.修改views.py

from django.shortcuts import render

# Create your views here.

def home(request):
    return render(request, 'index.html', locals())

5.建立templates目錄

6.把HTML程式存在templates目錄中,檔名是index.html



6.到Youtube上選擇一個影片

7.在影片上按下右鍵,選擇複製嵌入式程式碼選項。

8.把嵌入程式碼貼到HTML中

9.輸入下列指令啟動網站
python manage.py makemigrations
python manage.py migrate
python manage.py runserver

10.打開瀏覽器輸入127.0.0.1:8000查看結果

下一篇文章:影片網站資料庫及後台管理(二) - 視圖和樣版