iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 10
0
Modern Web

使用 Django 開發網頁系統系列 第 10

[Day 10] 新增資料

今天來寫 新增 category

http 協定在網頁上用的是 GET 跟 POST

GET 就是 一般的網頁請求,像在瀏覽器輸入網址一樣

POST 比較安全 會拿來用資料新增,修改...等

UI上多了一個新增按鈕

點擊新增出現 表單
點了儲存就發post request

這裡就一次寫完了
store/urls.py

urlpatterns = [
    ...
    path('categoryCreate/', views.categoryCreate)
]

新增一個function

request.method 來判斷是 GET or POST
request.POST.get('') 是抓表單的資料
<class>() 是new空的物件
<class>.<filed> 把值塞進去
<class>.save() 儲存
redirect() 重新導向 302 去到下一個路徑
如果不寫的話,按重新整理會在重送上一個post請求
store/views.py

def categoryCreate(request):
    if request.method == 'GET':
        return render(request, 'store/categoryCreate.html')
    elif request.method == 'POST':
        name = request.POST.get('name')
        category = Category()
        category.name = name
        category.save()
        return redirect('/store/category/')

在django form 表單如果是post 需要再多 csrf_token 欄位

store/templates/store/categoryCreate.htnl

<!doctype html>
<html>
<head></head>
<body>

<h3>新增類別</h3>
<form method="post" action="/store/categoryCreate/">
  {% csrf_token %}
  <div>
    <label for="name">名稱</label>
    <input id="name" name="name">
  </div>

  <input type="submit" value="儲存">
</form>

</body>
</html>

store/templates/store/category.htnl

...
<a href="/store/categoryCreate/">新增</a>
...

今天就完成了新增資料
明天再講重購的部分,還有驗證 等等


上一篇
[Day 09] 顯示全部資料
下一篇
[Day 11] 重構表單-forms.py
系列文
使用 Django 開發網頁系統30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言