回上方

實戰:記帳

接續上一個assistant專案與web應用程式。

資料庫

開啟 assistant/web/models.py,新增以下程式碼:

# 帳目 class Money(models.Model): CHOICES = ( (1, "飲食"), (2, "衣服"), (3, "交通"), (4, "教育"), (5, "娛樂"), (6, "其它"), ) item = models.CharField(max_length=30, verbose_name='項目') kind = models.IntegerField(default=0, choices=CHOICES, verbose_name='類別') price = models.IntegerField(default=0, verbose_name='金額') time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.item

在終端機中按下Ctrl+C中斷程式執行,回到命令提示模式。在終端機執行以下指令建立資料庫

python manage.py makemigrations python manage.py migrate

開啟網站服務

python manage.py runserver 0:80

視圖、網址、範本、表單

我們要建立相對應的網頁,開啟assistant/web/urls.py,新增以下程式碼。

path('money', MoneyList.as_view()), path('money/create/', MoneyCreate.as_view()), path('money/<int:pk>/update/', MoneyUpdate.as_view()), path('money/<int:pk>/delete/', MoneyDelete.as_view()),

開啟 assistant/web/views.py,新增以下程式碼。

from .models import Money class MoneyList(LoginRequiredMixin, ListView): model = Money ordering = ['-id'] paginate_by = 3 class MoneyCreate(LoginRequiredMixin, CreateView): model = Money fields = '__all__' success_url = "/web/money" template_name = 'form.html' class MoneyUpdate(LoginRequiredMixin, UpdateView): model = Money fields = '__all__' success_url = "/web/money" template_name = 'form.html' class MoneyDelete(LoginRequiredMixin, DeleteView): model = Money success_url = "/web/money" template_name = 'confirm_delete.html'

開啟檔案 assistant/templates/base.html,修改為以下程式碼: 第10-11行

<!DOCTYPE html> <html> <head> </head> <body> <h1>數位助理</h1> {% if user.is_authenticated %} <a href="/journal">日記</a> <a href="/journal/create">寫日誌</a> <a href="/money">帳本</a> <a href="/money/create">記帳</a> {{ user.username }} <a href="/accounts/logout">登出</a> {% else %} <a href="/accounts/login">登入</a> {% endif %} {% block content %} {% endblock %} </body> </html>

新增檔案 assistant/templates/web/money_list.html

{% extends "base.html" %} {% block content %} <h1>我的帳本:</h1> <table> <tr> <td>時間</td> <td>項目</td> <td>類別</td> <td>金額</td> <td>功能</td></tr> {% for money in money_list %} <tr> <td>({{money.time| date:"l"}}){{money.time}}</td></td> <td><a href="money/{{money.id}}/update/">{{money.item}}</td> <td>{{money.get_kind_display}}</td> <td>{{money.price}}</a></td>  <td><a href="money/{{money.id}}/delete/">刪除</a></td> </tr> {% endfor %} </table> {% endblock %}