iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
2
Modern Web

🍐放學後的網頁開發系列 第 25

[Day25] 柚子放學後的網頁生活 - Django Photo sharing

回來囉,上次完成會員註冊、登入登出
這篇要讓你可以開始PO些文章囉~

Get Photo

讓我們很快複習一下開發流程 ...

這邊建立一個create_photo.html,可以借用signup.html改以下這段

HTML part

<div class="container">
       <h1>Share Photos</h1>
       <form method="POST" action="/photo/create/post">
         <label>Photo's title</label>
         <input class="form-control" type="text" name="title">
         <label>Photo's path</label>
         <input class="form-control" type="text" name="path">
         <label>Tell a story</label>
         <input class="form-control" type="text" name="story"><br>
         {% csrf_token %}
         <button class="btn btn-primary btn-block">Submit</button>
       </form>
</div>

URL part

from photos.views import get_photos_api, get_create_photo

url(r'^photo/create',get_create_photo)

View part

這邊就是簡單的render出來

def get_create_photo(request):
    return render(request,'create_photo.html')

以上都完成後,記得確認navbar的POST button 連結是否是到create_photo.html

先看看...

很好 ! 非常迅速的成功了 ~

Create Photo

這邊就是把讓剛剛的Form變得有意義,確實新建到資料庫!

URL part

from photos.views import get_photos_api, get_create_photo ,post_create_photo

url(r'^photo/create/post',post_create_photo),

View part

我們import一個django的package forms

from django import forms
class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ['title','path','story']

因為create是用POST,request後建立我們的object,再去檢查是否valid,確認就save起來redirect回index,失敗的話就在原地

def post_create_photo(request):
    if request.method=='POST':
        form = PhotoForm(request.POST)
        if form.is_valid():
            new_photo = form.save()
            print(new_photo)
            return redirect('/index')
        else:
            return redirect('/photo/create')

TRY

...
...

這樣就成功囉 !!

下課囉 ~ 請鎖定 柚子放學後的網頁生活


上一篇
[Day24] 柚子放學後的網頁生活 - Web Crawler
下一篇
[Day26] 柚子放學後的網頁生活 - Flask intro
系列文
🍐放學後的網頁開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言