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支影片

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

沒有留言:

張貼留言