├── .gitignore ├── It's django 範例碼使用指南.pdf ├── LICENSE ├── README.md ├── cover.jpg ├── mysite ├── bank │ ├── __init__.py │ ├── actions.py │ ├── admin.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── configs │ ├── apache2 │ │ ├── 000-default.conf │ │ └── 000-default_with_ssl.conf │ ├── nginx │ │ ├── default │ │ └── default_with_ssl │ └── uwsgi │ │ ├── apt │ │ ├── mysite.ini │ │ └── uwsgi.conf │ │ └── pip │ │ ├── mysite.ini │ │ └── uwsgi.conf ├── manage.py ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── tests.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── restaurants │ ├── __init__.py │ ├── admin.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20141210_1828.py │ │ ├── 0003_comment.py │ │ ├── 0004_auto_20141216_1211.py │ │ └── __init__.py │ ├── models.py │ ├── permissions.py │ ├── templates │ │ ├── comments.html │ │ ├── menu.html │ │ └── restaurants_list.html │ ├── templatetags │ │ ├── __init__.py │ │ └── myfilters.py │ ├── tests.py │ └── views.py ├── templates │ ├── base.html │ ├── index.html │ ├── math.html │ ├── register.html │ ├── registration │ │ ├── logged_out.html │ │ └── login.html │ └── welcome.html └── zoo │ ├── __init__.py │ ├── admin.py │ ├── fixtures │ └── dog.json │ ├── migrations │ ├── 0001_initial.py │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # PyInstaller 26 | # Usually these files are written by a python script from a template 27 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 28 | *.manifest 29 | *.spec 30 | 31 | # Installer logs 32 | pip-log.txt 33 | pip-delete-this-directory.txt 34 | 35 | # Unit test / coverage reports 36 | htmlcov/ 37 | .tox/ 38 | .coverage 39 | .cache 40 | nosetests.xml 41 | coverage.xml 42 | 43 | # Translations 44 | *.mo 45 | *.pot 46 | 47 | # Django stuff: 48 | *.log 49 | 50 | # Sphinx documentation 51 | docs/_build/ 52 | 53 | # PyBuilder 54 | target/ 55 | -------------------------------------------------------------------------------- /It's django 範例碼使用指南.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/It's django 範例碼使用指南.pdf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## It's Django -- 用Python迅速打造Web應用 2 | 3 | 這是就 Django1.8 以上的版本所提供的範例碼專案。我們將陸續就升級至1.8版作說明。 4 | 其餘有關於本書的各種資訊,還是請讀者於原本專案(適用於Django1.7版)的github wiki上取得: 5 | * [前往本書wiki](https://github.com/its-django/mysite/wiki) 6 | 7 | ### wiki目錄 8 | * [wiki首頁](https://github.com/its-django/mysite/wiki/) 9 | * [本書資訊](https://github.com/its-django/mysite/wiki/本書資訊) 10 | * [如何取得本書](https://github.com/its-django/mysite/wiki/本書資訊#如何取得本書) 11 | * [作者介紹](https://github.com/its-django/mysite/wiki/本書資訊#作者介紹) 12 | * [範例碼](https://github.com/its-django/mysite/wiki/範例碼) 13 | * [適用版本](https://github.com/its-django/mysite/wiki/範例碼#適用版本) 14 | * [使用說明](https://github.com/its-django/mysite/wiki/範例碼#使用說明) 15 | * [範例碼分支架構](https://github.com/its-django/mysite/wiki/範例碼#範例碼分支架構) 16 | * [使用git下載與操作](https://github.com/its-django/mysite/wiki/範例碼#使用git下載與操作) 17 | * [代碼打包下載](https://github.com/its-django/mysite/wiki/範例碼#代碼打包下載) 18 | * [社群與互動](https://github.com/its-django/mysite/wiki/社群與互動) 19 | * [勘誤](https://github.com/its-django/mysite/wiki/勘誤) 20 | * [錯漏多字勘誤總表](https://github.com/its-django/mysite/wiki/勘誤/#錯字勘誤總表) 21 | * [重要參數勘誤表](https://github.com/its-django/mysite/wiki/勘誤/#重要參數勘誤表) 22 | * [開發步驟勘誤](https://github.com/its-django/mysite/wiki/勘誤/#開發步驟勘誤) 23 | * [程式碼勘誤表](https://github.com/its-django/mysite/wiki/勘誤/#程式碼勘誤表) 24 | * [學習資源](https://github.com/its-django/mysite/wiki/學習資源) 25 | * [部落格教學](https://github.com/its-django/mysite/wiki/學習資源/#部落格教學) 26 | * [相關網站](https://github.com/its-django/mysite/wiki/學習資源/#相關網站) 27 | * [好評](https://github.com/its-django/mysite/wiki/好評) 28 | 29 | ### 如何取得本書 30 | 31 | 實體書的購買管道請參考各出版社合作之[通路](http://books.gotop.com.tw/v_ACL043800) 32 | 33 | 電子書可以在[Google Play](https://play.google.com/store/books/details/%E8%A2%81%E5%85%8B%E5%80%AB_%E6%A5%8A%E5%AD%9F%E7%A9%8E_It_s_Django_%E7%94%A8Python%E8%BF%85%E9%80%9F%E6%89%93%E9%80%A0Web%E6%87%89%E7%94%A8_%E9%9B%BB%E5%AD%90%E6%9B%B8?id=C5UVCgAAQBAJ)上購買 34 | -------------------------------------------------------------------------------- /cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/cover.jpg -------------------------------------------------------------------------------- /mysite/bank/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/bank/__init__.py -------------------------------------------------------------------------------- /mysite/bank/actions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | import logging 5 | 6 | from django.db import transaction 7 | 8 | logging.basicConfig() 9 | logger = logging.getLogger(__name__) 10 | logger.setLevel(logging.INFO) 11 | 12 | 13 | @transaction.atomic 14 | def transfer_money(_from, _to, quota): 15 | 16 | if _from.money < 15: 17 | raise ValueError("連手續費都付不起,請回吧!!") 18 | 19 | _from.money = _from.money - 15 20 | _from.save() 21 | 22 | sid = transaction.savepoint() 23 | 24 | try: 25 | _from.money = _from.money - quota 26 | if _from.money < 0: 27 | raise ValueError("超額提領!") 28 | _from.save() 29 | _to.money = _to.money + quota 30 | if _to.money > 100000: 31 | raise ValueError("超額儲存!") 32 | _to.save() 33 | transaction.savepoint_commit(sid) 34 | except ValueError as e: 35 | logger.error("金額操作錯誤, 訊息:<{}>".format(e)) 36 | transaction.savepoint_rollback(sid) 37 | except Exception as e: 38 | logger.error("其他錯誤,訊息:<{}>".format(e)) 39 | transaction.savepoint_rollback(sid) 40 | -------------------------------------------------------------------------------- /mysite/bank/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /mysite/bank/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Account', 15 | fields=[ 16 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 17 | ('name', models.CharField(max_length=64)), 18 | ('money', models.IntegerField()), 19 | ], 20 | options={ 21 | }, 22 | bases=(models.Model,), 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /mysite/bank/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/bank/migrations/__init__.py -------------------------------------------------------------------------------- /mysite/bank/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Account(models.Model): 5 | 6 | """Simple Bank account with name and money. """ 7 | 8 | name = models.CharField(max_length=64) 9 | money = models.IntegerField() 10 | -------------------------------------------------------------------------------- /mysite/bank/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /mysite/bank/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /mysite/configs/apache2/000-default.conf: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 改為你的email 4 | ServerAdmin your_email@gmail.com 5 | 6 | # 改至Django根目錄 7 | DocumentRoot /var/www/source/django/mysite 8 | 9 | # 參考前一小節設定,將settings.py中設定的STATIC_URL導向STATIC_ROOT位置 10 | # 需寫在WSGIScriptAlias前面,攔截靜態路徑,否則傳至django也不會被處理 11 | Alias /static/ /var/www/source/django/mysite/assets/ 12 | 13 | # 第一個"/"為網址例的匹配,這裡用"/"表示全部的匹配都導向django 14 | # 所以第二個參數填寫至wsgi.py的完整路徑 15 | WSGIScriptAlias / /var/www/source/django/mysite/mysite/wsgi.py 16 | 17 | # 加入django根目錄及系統上python lib的路徑 18 | WSGIDaemonProcess mysite python-path=/var/www/source/django/mysite:/usr/loca/lib/python2.7/dict-packages 19 | WSGIProcessGroup mysite 20 | 21 | 22 | 23 | = 2.4> 24 | Require all granted 25 | 26 | 27 | Order deny,allow 28 | Allow from all 29 | 30 | 31 | 32 | 33 | ErrorLog ${APACHE_LOG_DIR}/error.log 34 | CustomLog ${APACHE_LOG_DIR}/access.log combined 35 | 36 | 37 | -------------------------------------------------------------------------------- /mysite/configs/apache2/000-default_with_ssl.conf: -------------------------------------------------------------------------------- 1 | # 檢查是否有ssl模組 2 | 3 | # 改port為443 (https預設的port) 4 | 5 | 6 | ServerAdmin your_email@gmail.com 7 | DocumentRoot /var/www/source/django/mysite 8 | 9 | Alias /static/ /var/www/source/django/mysite/assets/ 10 | 11 | WSGIScriptAlias / /var/www/source/django/mysite/mysite/wsgi.py 12 | WSGIDaemonProcess mysite python-path=/var/www/source/django/mysite:/home/user1/.virtualenvs/django/lib/python2.7/site-packages 13 | WSGIProcessGroup mysite 14 | 15 | # 加入 ssl 設定 16 | SSLEngine on 17 | SSLCertificateFile /etc/apache2/self_signed_ssl/apache.crt 18 | SSLCertificateKeyFile /etc/apache2/self_signed_ssl/apache.key 19 | 20 | 21 | 22 | = 2.4> 23 | Require all granted 24 | 25 | 26 | Order deny,allow 27 | Allow from all 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /mysite/configs/nginx/default: -------------------------------------------------------------------------------- 1 | # 定義一個名為django的來源,用Nginx反向代理的特性,跟定義的server交換資料 2 | upstream django { 3 | # 定義一個假的server,記得我們設定uwsgi是從mysite_uwsgi.sock交換資料? 4 | # 而Nginx也從這個檔案交換資料,如此一來便把兩邊串接起來 5 | server unix:///var/run/mysite_uwsgi.sock; 6 | } 7 | 8 | server { 9 | # 監聽的 port 10 | listen 80 default_server; 11 | 12 | # 伺服器網域或ip 13 | server_name yourdomain.com; 14 | 15 | location / { 16 | # 把匹配的請求傳至 django 17 | uwsgi_pass django; 18 | # 記得載入nginx uwsgi_params 19 | include /etc/nginx/uwsgi_params; 20 | } 21 | 22 | # 匹配到static時讓nginx直接到static folder取靜態檔,無需透過uwsgi及django 23 | location ~ /static/ { 24 | alias /var/www/source/django/mysite/assets/; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /mysite/configs/nginx/default_with_ssl: -------------------------------------------------------------------------------- 1 | upstream django { 2 | server unix:///var/run/mysite_uwsgi.sock; 3 | } 4 | 5 | server { 6 | 7 | server_name yourdomain.com; 8 | 9 | # 監聽 443,80 port可以關閉或並存 10 | listen 443 ssl; 11 | # 憑證檔位置 12 | ssl_certificate /etc/nginx/self_signed_ssl/nginx.crt; 13 | ssl_certificate_key /etc/nginx/self_signed_ssl/nginx.key; 14 | 15 | # ssl相關設定 16 | ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 17 | ssl_ciphers RC4:HIGH:!aNULL:!MD5; 18 | ssl_prefer_server_ciphers on; 19 | 20 | location / { 21 | uwsgi_pass django; 22 | include /etc/nginx/uwsgi_params; 23 | } 24 | 25 | location ~ /static/ { 26 | alias /path/to/your/static/; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /mysite/configs/uwsgi/apt/mysite.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | # Django相關設定 3 | # 根目錄(完整路徑) 4 | chdir = /var/www/source/django/mysite 5 | # django project 下的 wsgi.file 6 | module = mysite.wsgi 7 | # 系統 python 及 site-packages 位置 8 | pythonpath = /usr/local/lib/python2.7 9 | pythonpath = /usr/local/lib/python2.7/dist-packages 10 | 11 | # Process (行程)設定 12 | master = true 13 | processes = 4 14 | # socket 檔案讓伺服器和應用程式透過系統溝通,而非再經由網路 15 | socket = /var/run/mysite_uwsgi.sock 16 | pidfile = /var/run/mysite_uwsgi.pid 17 | # socket 檔的權限 18 | chmod-socket = 666 19 | # 清除產生的檔案 20 | vacuum = true 21 | 22 | # !!! 主要與pip不同在這裡 !!! 23 | logto = /var/log/mysite_uwsgi.log 24 | plugins = python 25 | 26 | optmize = true 27 | -------------------------------------------------------------------------------- /mysite/configs/uwsgi/apt/uwsgi.conf: -------------------------------------------------------------------------------- 1 | # simple uWSGI script in /etc/init/ 2 | 3 | description "uwsgi upstart service" 4 | start on runlevel [2345] 5 | stop on runlevel [!2345] 6 | respawn 7 | 8 | exec /usr/bin/uwsgi --ini /var/www/source/django/mysite/mysite.ini 9 | -------------------------------------------------------------------------------- /mysite/configs/uwsgi/pip/mysite.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | # Django相關設定 3 | # 根目錄(完整路徑) 4 | chdir = /var/www/source/django/mysite 5 | # django project 下的 wsgi.file 6 | module = mysite.wsgi 7 | # 系統 python 及 site-packages 位置 8 | pythonpath = /usr/local/lib/python2.7 9 | pythonpath = /usr/local/lib/python2.7/dist-packages 10 | 11 | # Process (行程)設定 12 | master = true 13 | processes = 4 14 | # socket 檔案讓伺服器和應用程式透過系統溝通,而非再經由網路 15 | socket = /var/run/mysite_uwsgi.sock 16 | pidfile = /var/run/mysite_uwsgi.pid 17 | # socket 檔的權限 18 | chmod-socket = 666 19 | # 清除產生的檔案 20 | vacuum = true 21 | 22 | # 指定日誌檔路徑便可 daemon 化 23 | daemonize = /var/log/mysite_uwsgi_daemonize.log 24 | 25 | optmize = true 26 | -------------------------------------------------------------------------------- /mysite/configs/uwsgi/pip/uwsgi.conf: -------------------------------------------------------------------------------- 1 | # simple uWSGI script in /etc/init/ 2 | 3 | description "uwsgi upstart service" 4 | start on runlevel [2345] 5 | stop on runlevel [!2345] 6 | respawn 7 | 8 | exec /usr/local/bin/uwsgi --ini /var/www/source/django/mysite/mysite.ini 9 | -------------------------------------------------------------------------------- /mysite/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /mysite/mysite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/mysite/__init__.py -------------------------------------------------------------------------------- /mysite/mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.8.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.8/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.8/ref/settings/ 11 | """ 12 | 13 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 14 | import os 15 | 16 | from django.conf import global_settings 17 | 18 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 19 | 20 | 21 | # Quick-start development settings - unsuitable for production 22 | # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ 23 | 24 | # SECURITY WARNING: keep the secret key used in production secret! 25 | SECRET_KEY = 'gz909_-)w*ppzuj=*kppx0nrari4v27i9@02ic7+=i*9yq8%r5' 26 | 27 | # SECURITY WARNING: don't run with debug turned on in production! 28 | DEBUG = True 29 | 30 | ALLOWED_HOSTS = [] 31 | 32 | 33 | # Application definition 34 | 35 | INSTALLED_APPS = ( 36 | 'django.contrib.admin', 37 | 'django.contrib.auth', 38 | 'django.contrib.contenttypes', 39 | 'django.contrib.sessions', 40 | 'django.contrib.messages', 41 | 'django.contrib.staticfiles', 42 | 'restaurants', 43 | 'bank', 44 | 'zoo', 45 | ) 46 | 47 | MIDDLEWARE_CLASSES = ( 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.common.CommonMiddleware', 50 | 'django.middleware.csrf.CsrfViewMiddleware', 51 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | 'django.middleware.security.SecurityMiddleware', 56 | ) 57 | 58 | ROOT_URLCONF = 'mysite.urls' 59 | 60 | TEMPLATES = [ 61 | { 62 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 63 | 'DIRS': [ 64 | os.path.join(BASE_DIR, 'templates'), 65 | ], 66 | 'APP_DIRS': True, 67 | 'OPTIONS': { 68 | 'context_processors': [ 69 | 'django.template.context_processors.debug', 70 | 'django.template.context_processors.request', 71 | 'django.contrib.auth.context_processors.auth', 72 | 'django.contrib.messages.context_processors.messages', 73 | ], 74 | }, 75 | }, 76 | ] 77 | 78 | WSGI_APPLICATION = 'mysite.wsgi.application' 79 | 80 | 81 | # Database 82 | # https://docs.djangoproject.com/en/1.8/ref/settings/#databases 83 | 84 | DATABASES = { 85 | 'default': { 86 | 'ENGINE': 'django.db.backends.sqlite3', 87 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 88 | } 89 | } 90 | 91 | 92 | # Internationalization 93 | # https://docs.djangoproject.com/en/1.8/topics/i18n/ 94 | 95 | LANGUAGE_CODE = 'zh-TW' 96 | 97 | TIME_ZONE = 'Asia/Taipei' 98 | 99 | USE_I18N = True 100 | 101 | USE_L10N = True 102 | 103 | USE_TZ = True 104 | 105 | 106 | # Static files (CSS, JavaScript, Images) 107 | # https://docs.djangoproject.com/en/1.8/howto/static-files/ 108 | 109 | STATIC_URL = '/static/' 110 | 111 | SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' 112 | 113 | LOGIN_REDIRECT_URL = "/index/" 114 | 115 | TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + ( 116 | 'django.core.context_processors.request', 117 | ) 118 | 119 | FIXTURE_DIRS = ( 120 | os.path.join(BASE_DIR, 'fixtures'), 121 | ) 122 | -------------------------------------------------------------------------------- /mysite/mysite/tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | 5 | from django.test import TestCase 6 | from django.contrib.auth.models import User 7 | from django.test import client 8 | 9 | 10 | class IndexWebpageTestCase(TestCase): 11 | 12 | """Simple Webpage visiting test""" 13 | 14 | def setUp(self): 15 | """setUp function 16 | :returns: TODO 17 | 18 | """ 19 | self.c = client.Client() 20 | 21 | def test_index_visiting(self): 22 | """simple index visiting 23 | :returns: TODO 24 | 25 | """ 26 | resp = self.c.get('/index/') 27 | self.assertEqual(resp.status_code, 200) 28 | self.assertContains(resp, '

歡迎來到餐廳王

') 29 | self.assertTemplateUsed(resp, 'index.html') 30 | 31 | 32 | class LoginTestCase(TestCase): 33 | 34 | """Login test case""" 35 | 36 | def setUp(self): 37 | """create user 38 | :returns: TODO 39 | 40 | """ 41 | User.objects.create_user('user', email='user@example.com', password='abcde') 42 | self.c = client.Client() 43 | 44 | def test_login_and_logout(self): 45 | """test login method using django auth 46 | 47 | """ 48 | 49 | resp = self.c.get('/restaurants_list/') 50 | self.assertRedirects(resp, '/accounts/login/?next=/restaurants_list/') 51 | 52 | self.c.login(username='user', password='abcde') 53 | 54 | resp = self.c.get('/restaurants_list/') 55 | self.assertEqual(resp.status_code, 200) 56 | self.assertTemplateUsed(resp, 'restaurants_list.html') 57 | 58 | self.c.logout() 59 | resp = self.c.get('/restaurants_list/') 60 | self.assertRedirects(resp, '/accounts/login/?next=/restaurants_list/') 61 | 62 | def test_login_and_logout_by_http_protocol(self): 63 | """test login method using django auth 64 | 65 | """ 66 | 67 | resp = self.c.get('/restaurants_list/') 68 | self.assertRedirects(resp, '/accounts/login/?next=/restaurants_list/') 69 | 70 | resp = self.c.post( 71 | '/accounts/login/', {'username': 'user', 'password': 'abcde'}, follow=True) 72 | self.assertEqual(resp.redirect_chain, [('http://testserver/index/', 302)]) 73 | 74 | resp = self.c.get('/restaurants_list/') 75 | self.assertEqual(resp.status_code, 200) 76 | self.assertTemplateUsed(resp, 'restaurants_list.html') 77 | 78 | self.c.get('/accounts/logout/') 79 | resp = self.c.get('/restaurants_list/') 80 | self.assertRedirects(resp, '/accounts/login/?next=/restaurants_list/') 81 | -------------------------------------------------------------------------------- /mysite/mysite/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import include, url 2 | from django.contrib import admin 3 | admin.autodiscover() 4 | 5 | from django.contrib.auth.views import login, logout 6 | from django.views.generic.base import TemplateView 7 | 8 | from . import views 9 | import restaurants.views 10 | 11 | 12 | urlpatterns = [ 13 | url(r'^accounts/login/$', login), 14 | url(r'^accounts/logout/$', logout), 15 | url(r'^admin/', include(admin.site.urls)), 16 | 17 | url('^index/$', TemplateView.as_view(template_name='index.html')), 18 | url(r'^accounts/register/$', views.register), 19 | url(r'^here/$', views.HereView.as_view()), 20 | url(r'^(\d{1,2})/math/(\d{1,2})/$', views.math), 21 | url(r'^welcome/$', views.welcome), 22 | 23 | url(r'^menu/(?P\d+)/$', restaurants.views.MenuView.as_view()), 24 | url(r'^restaurants_list/$', restaurants.views.RestaurantsView.as_view()), 25 | url(r'^comment/(?P\d+)/$', restaurants.views.CommentView.as_view()), 26 | ] 27 | -------------------------------------------------------------------------------- /mysite/mysite/views.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | from django.contrib import auth 4 | from django.contrib.auth.forms import UserCreationForm 5 | from django.http import HttpResponse, HttpResponseRedirect 6 | from django.shortcuts import render_to_response, render 7 | from django.template import RequestContext 8 | from django.views.generic.base import View, TemplateView 9 | 10 | 11 | def math(request, a, b): 12 | a = int(a) 13 | b = int(b) 14 | s = a + b 15 | d = a - b 16 | p = a * b 17 | q = a / b 18 | return render_to_response('math.html', {'s': s, 'd': d, 'p': p, 'q': q}) 19 | 20 | 21 | def welcome(request): 22 | """simple welcome page to demo query string 23 | 24 | :request: user request 25 | :returns: http response with username or origin welcome page 26 | 27 | """ 28 | if 'user_name' in request.GET and request.GET['user_name'] != '': 29 | return HttpResponse('Welcome!~'+request.GET['user_name']) 30 | else: 31 | return render_to_response('welcome.html', locals()) 32 | 33 | 34 | def login(request): 35 | """user login webpage 36 | 37 | :request: client request 38 | :returns: index page if success, login page if fail 39 | 40 | """ 41 | if request.user.is_authenticated(): 42 | return HttpResponseRedirect('/index/') 43 | 44 | username = request.POST.get('username', '') 45 | password = request.POST.get('password', '') 46 | 47 | user = auth.authenticate(username=username, password=password) 48 | 49 | if user is not None and user.is_active: 50 | auth.login(request, user) 51 | return HttpResponseRedirect('/index/') 52 | else: 53 | return render_to_response('login.html', RequestContext(request, locals())) 54 | 55 | 56 | def logout(request): 57 | """logout view 58 | 59 | :request: client request 60 | :returns: index webpage 61 | 62 | """ 63 | auth.logout(request) 64 | return HttpResponseRedirect('/index/') 65 | 66 | 67 | def register(request): 68 | """new user register page 69 | 70 | :request: client request 71 | :returns: redirect to login page if success else register page 72 | 73 | """ 74 | if request.method == 'POST': 75 | form = UserCreationForm(request.POST) 76 | if form.is_valid(): 77 | user = form.save() 78 | return HttpResponseRedirect('/accounts/login/') 79 | else: 80 | form = UserCreationForm() 81 | return render(request, 'register.html', locals()) 82 | 83 | 84 | class HereView(View): 85 | """first class view 86 | """ 87 | 88 | def get(self, request): 89 | """process http GET 90 | 91 | :request: request 92 | :returns: response 93 | 94 | """ 95 | return HttpResponse('媽,我在這!') 96 | 97 | 98 | class IndexView(TemplateView): 99 | 100 | """rewrite index view with class-based view""" 101 | 102 | template_name = 'index.html' 103 | -------------------------------------------------------------------------------- /mysite/mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /mysite/restaurants/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/restaurants/__init__.py -------------------------------------------------------------------------------- /mysite/restaurants/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from restaurants.models import Restaurant, Food, Comment 3 | 4 | 5 | class RestaurantAdmin(admin.ModelAdmin): 6 | list_display = ('name', 'phone_number', 'address') 7 | search_fields = ('name',) 8 | 9 | 10 | class FoodAdmin(admin.ModelAdmin): 11 | list_display = ('name', 'restaurant', 'price') 12 | list_filter = ('is_spicy',) 13 | ordering = ('-price',) 14 | fields = ('price', 'restaurant') 15 | 16 | 17 | admin.site.register(Restaurant, RestaurantAdmin) 18 | admin.site.register(Food, FoodAdmin) 19 | admin.site.register(Comment) 20 | -------------------------------------------------------------------------------- /mysite/restaurants/forms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | from django import forms 5 | 6 | 7 | class CommentForm(forms.Form): 8 | 9 | """Comment Form class clear""" 10 | 11 | visitor = forms.CharField(max_length=20) 12 | email = forms.EmailField(max_length=20, required=False) 13 | content = forms.CharField(max_length=200, widget=forms.Textarea()) 14 | 15 | def clean_content(self): 16 | """check content if len > 5 17 | :returns: cleaned content 18 | 19 | """ 20 | content = self.cleaned_data.get('content', '') 21 | if len(content) < 5: 22 | raise forms.ValidationError('字數不足') 23 | return content 24 | -------------------------------------------------------------------------------- /mysite/restaurants/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Food', 15 | fields=[ 16 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 17 | ('name', models.CharField(max_length=20)), 18 | ('price', models.DecimalField(max_digits=3, decimal_places=0)), 19 | ('comment', models.CharField(max_length=50, blank=True)), 20 | ('is_spicy', models.BooleanField(default=False)), 21 | ], 22 | options={ 23 | }, 24 | bases=(models.Model,), 25 | ), 26 | migrations.CreateModel( 27 | name='Restaurant', 28 | fields=[ 29 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 30 | ('name', models.CharField(max_length=20)), 31 | ('phone_number', models.CharField(max_length=15)), 32 | ('address', models.CharField(max_length=50, blank=True)), 33 | ], 34 | options={ 35 | }, 36 | bases=(models.Model,), 37 | ), 38 | migrations.AddField( 39 | model_name='food', 40 | name='restaurant', 41 | field=models.ForeignKey(to='restaurants.Restaurant'), 42 | preserve_default=True, 43 | ), 44 | ] 45 | -------------------------------------------------------------------------------- /mysite/restaurants/migrations/0002_auto_20141210_1828.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('restaurants', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterModelOptions( 15 | name='food', 16 | options={'ordering': ['price']}, 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /mysite/restaurants/migrations/0003_comment.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('restaurants', '0002_auto_20141210_1828'), 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Comment', 16 | fields=[ 17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 18 | ('content', models.CharField(max_length=255)), 19 | ('visitor', models.CharField(max_length=255)), 20 | ('email', models.EmailField(max_length=255)), 21 | ('date_time', models.DateTimeField()), 22 | ('restaurant', models.ForeignKey(to='restaurants.Restaurant')), 23 | ], 24 | options={ 25 | }, 26 | bases=(models.Model,), 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /mysite/restaurants/migrations/0004_auto_20141216_1211.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('restaurants', '0003_comment'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterModelOptions( 15 | name='comment', 16 | options={'permissions': (('can_comment', 'Can comment'),)}, 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /mysite/restaurants/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/restaurants/migrations/__init__.py -------------------------------------------------------------------------------- /mysite/restaurants/models.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | from django.db import models 5 | 6 | 7 | class Restaurant(models.Model): 8 | name = models.CharField(max_length=20) 9 | phone_number = models.CharField(max_length=15) 10 | address = models.CharField(max_length=50, blank=True) 11 | 12 | def __unicode__(self): 13 | """ 14 | :returns: name string 15 | 16 | """ 17 | return self.name 18 | 19 | 20 | class Food(models.Model): 21 | name = models.CharField(max_length=20) 22 | price = models.DecimalField(max_digits=3, decimal_places=0) 23 | comment = models.CharField(max_length=50, blank=True) 24 | is_spicy = models.BooleanField(default=False) 25 | restaurant = models.ForeignKey(Restaurant) 26 | 27 | def __unicode__(self): 28 | """ 29 | :returns: name string 30 | 31 | """ 32 | return self.name 33 | 34 | class Meta: 35 | 36 | """Meta: attribute, options""" 37 | 38 | ordering = ['price'] 39 | 40 | 41 | class Comment(models.Model): 42 | 43 | """ commment model """ 44 | 45 | content = models.CharField(max_length=255) 46 | visitor = models.CharField(max_length=255) 47 | email = models.EmailField(max_length=255) 48 | date_time = models.DateTimeField() 49 | restaurant = models.ForeignKey(Restaurant) 50 | 51 | class Meta: 52 | permissions = ( 53 | ("can_comment", "Can comment"), 54 | ) 55 | -------------------------------------------------------------------------------- /mysite/restaurants/permissions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | 5 | def user_can_comment(user): 6 | """check if user has permission to comment 7 | 8 | :user: user to be check 9 | :returns: boolean 10 | 11 | """ 12 | return user.is_authenticated and user.has_perm('restaurants.can_comment') 13 | -------------------------------------------------------------------------------- /mysite/restaurants/templates/comments.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} Comment {% endblock %} 4 | 5 | {% block content %} 6 |

{{ r.name }}的評價

7 | {% if r.comment_set.all %} 8 |

目前共有{{ r.comment_set.all|length }}條評價

9 | 10 | 11 | 12 | 13 | 14 | 15 | {% for c in r.comment_set.all %} 16 | 17 | 18 | 19 | 20 | 21 | {% endfor %} 22 |
留言者時間評價
{{ c.visitor }} {{ c.date_time | date:"F j, Y" }} {{ c.content }}
23 | {% else %} 24 |

無評價

25 | {% endif %} 26 | 27 |

28 | {% if form.errors %} 29 |

30 | 請依提示修復表單錯誤 31 |

32 | {% endif %} 33 | 34 |
{% csrf_token %} 35 |
36 | 37 | {{ form.visitor }} 38 | {{ form.visitor.errors }} 39 |
40 |
41 | 42 | {{ form.email }} 43 | {{ form.email.errors }} 44 |
45 |
46 | 47 | {{ form.content }} 48 | {{ form.content.errors }} 49 |
50 | 51 |
52 | {% endblock %} 53 | -------------------------------------------------------------------------------- /mysite/restaurants/templates/menu.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load myfilters %} 3 | 4 | {% block title %} Menu {% endblock %} 5 | 6 | {% block content %} 7 |

{{ restaurant.name }}的Menu

8 | {% if restaurant.food_set.all %} 9 |

本餐廳共有{{ restaurant.food_set.all|length }}道菜

10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | {% for food in restaurant.food_set.all %} 18 | 19 | 20 | 21 | 22 | 23 | 24 | {% endfor %} 25 |
菜名價格註解辣不辣
{{ food.name }} {{ food.price }} {{ food.comment }} {{ food.is_spicy|yes_no:"辣/不辣" }}
26 | {% else %} 27 |

本餐廳啥都沒賣

28 | {% endif %} 29 | {% endblock %} 30 | -------------------------------------------------------------------------------- /mysite/restaurants/templates/restaurants_list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} Restaurants {% endblock %} 4 | 5 | {% block content %} 6 |

餐廳列表

7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | {% for r in restaurants %} 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | {% endfor %} 24 |
選取店名電話地址評價
看菜單 {{ r.name }} {{ r.phone_number }} {{ r.address }} 評價
25 | {% endblock %} 26 | -------------------------------------------------------------------------------- /mysite/restaurants/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/restaurants/templatetags/__init__.py -------------------------------------------------------------------------------- /mysite/restaurants/templatetags/myfilters.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | from django import template 5 | 6 | register = template.Library() 7 | 8 | 9 | @register.filter(name='yes_no') 10 | def yes_no(bool_value, show_str): 11 | if bool_value: 12 | return show_str.partition('/')[0] 13 | else: 14 | return show_str.partition('/')[2] 15 | -------------------------------------------------------------------------------- /mysite/restaurants/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /mysite/restaurants/views.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | from django.http import HttpResponseRedirect 5 | from django.shortcuts import render_to_response, render 6 | from django.utils import timezone 7 | from django.contrib.auth.decorators import login_required, user_passes_test 8 | from django.views.generic.list import ListView 9 | from django.utils.decorators import method_decorator 10 | from django.views.generic.detail import DetailView, SingleObjectMixin 11 | from django.views.generic.edit import FormView 12 | 13 | from restaurants.models import Restaurant, Comment 14 | from restaurants.forms import CommentForm 15 | from restaurants.permissions import user_can_comment 16 | 17 | 18 | class MenuView(DetailView): 19 | 20 | """show restaurant menu""" 21 | 22 | model = Restaurant 23 | template_name = 'menu.html' 24 | context_object_name = 'restaurant' 25 | 26 | @method_decorator(login_required) 27 | def dispatch(self, request, *args, **kwargs): 28 | """ return decorated dispatch 29 | 30 | :request: request 31 | :returns: return origin dispatch 32 | """ 33 | return super(MenuView, self).dispatch(request, *args, **kwargs) 34 | 35 | 36 | class RestaurantsView(ListView): 37 | 38 | """return restaurant list""" 39 | 40 | model = Restaurant 41 | template_name = 'restaurants_list.html' 42 | context_object_name = 'restaurants' 43 | 44 | @method_decorator(login_required) 45 | def dispatch(self, request, *args, **kwargs): 46 | """ return decorated dispatch 47 | 48 | :request: request 49 | :returns: return origin dispatch 50 | """ 51 | return super(RestaurantsView, self).dispatch(request, *args, **kwargs) 52 | 53 | 54 | class CommentView(FormView, SingleObjectMixin): 55 | 56 | """View associated with form""" 57 | 58 | form_class = CommentForm 59 | template_name = 'comments.html' 60 | success_url = '/comment/' 61 | initial = {'content': u'我沒意見'} 62 | model = Restaurant 63 | context_object_name = 'r' 64 | 65 | def form_valid(self, form): 66 | """form is validated, so use form data to create comment 67 | 68 | :form: validated form 69 | :returns: origin form_valid 70 | 71 | """ 72 | Comment.objects.create( 73 | visitor=form.cleaned_data['visitor'], 74 | email=form.cleaned_data['email'], 75 | content=form.cleaned_data['content'], 76 | date_time=timezone.localtime(timezone.now()), 77 | restaurant=self.get_object() 78 | ) 79 | return self.render_to_response(self.get_context_data( 80 | form=self.form_class(initial=self.initial)) 81 | ) 82 | 83 | def get_context_data(self, **kwargs): 84 | """ assign attribute "object" that indicates the query object 85 | 86 | :returns: origin context get from get_context_data with additional object parameter 87 | 88 | """ 89 | self.object = self.get_object() 90 | return super(CommentView, self).get_context_data(object=self.object, **kwargs) 91 | 92 | @method_decorator(user_passes_test(user_can_comment, login_url='/accounts/login/')) 93 | def dispatch(self, request, *args, **kwargs): 94 | """ return decorated dispatch 95 | 96 | :request: request 97 | :returns: return origin dispatch 98 | """ 99 | return super(CommentView, self).dispatch(request, *args, **kwargs) 100 | -------------------------------------------------------------------------------- /mysite/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {% block title %} {% endblock %} 5 | 6 | 7 | 8 | 16 | 17 | 18 | 19 | 44 | 45 |
46 |
47 | {% block content %} {% endblock %} 48 |
49 |
50 | 51 | 52 | 53 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /mysite/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} 首頁 {% endblock %} 4 | 5 | {% block content %} 6 |

歡迎來到餐廳王

7 | {% if request.user.is_authenticated %} 8 | 餐廳列表 9 | {% else %} 10 |

您尚未登入喔~登入

11 |

若您還沒有帳號,請註冊

12 | {% endif %} 13 | {% endblock %} 14 | -------------------------------------------------------------------------------- /mysite/templates/math.html: -------------------------------------------------------------------------------- 1 | 2 | sum={{s}}
3 | dif={{d}}
4 | pro={{p}}
5 | quo={{q}} 6 | 7 | -------------------------------------------------------------------------------- /mysite/templates/register.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} Register {% endblock %} 4 | 5 | {% block content %} 6 |
{% csrf_token %} 7 | {{ form.as_p }} 8 | 9 |
10 | {% endblock %} 11 | -------------------------------------------------------------------------------- /mysite/templates/registration/logged_out.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} Logged out {% endblock %} 4 | 5 | {% block content %} 6 |

謝謝光臨!您已經登出

7 | 再次登入 8 | {% endblock %} 9 | -------------------------------------------------------------------------------- /mysite/templates/registration/login.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} Login {% endblock %} 4 | 5 | {% block content %} 6 |
{% csrf_token %} 7 | 8 | {{ form.as_table }} 9 |
10 | 11 | 12 |
13 | {% endblock %} 14 | -------------------------------------------------------------------------------- /mysite/templates/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Welcome 5 | 6 | 7 | 8 | 16 | 17 | 18 | 19 | 32 | 33 |
34 |
35 |
36 | 37 | 38 | 39 |
40 |
41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /mysite/zoo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/zoo/__init__.py -------------------------------------------------------------------------------- /mysite/zoo/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /mysite/zoo/fixtures/dog.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fields": { 4 | "name": "Snoopy" 5 | }, 6 | "model": "zoo.dog", 7 | "pk": 1 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /mysite/zoo/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Cat', 15 | fields=[ 16 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 17 | ('name', models.CharField(max_length=256)), 18 | ], 19 | options={ 20 | 'abstract': False, 21 | }, 22 | bases=(models.Model,), 23 | ), 24 | migrations.CreateModel( 25 | name='Dog', 26 | fields=[ 27 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 28 | ('name', models.CharField(max_length=256)), 29 | ], 30 | options={ 31 | 'abstract': False, 32 | }, 33 | bases=(models.Model,), 34 | ), 35 | ] 36 | -------------------------------------------------------------------------------- /mysite/zoo/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/its-django/mysite-django18/dc69cb4294eb53a1907ace4d9823c7d2163f7b46/mysite/zoo/migrations/__init__.py -------------------------------------------------------------------------------- /mysite/zoo/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Animal(models.Model): 5 | 6 | """ Base model of other animals""" 7 | 8 | name = models.CharField(max_length=256) 9 | 10 | def says(self): 11 | """implemented by different animal. 12 | 13 | """ 14 | raise NotImplementedError("I don't know what to say") 15 | 16 | class Meta: 17 | abstract = True 18 | 19 | 20 | class Dog(Animal): 21 | 22 | def says(self): 23 | """return sound of dog 24 | :returns: "woof" 25 | 26 | """ 27 | return 'woof' 28 | 29 | 30 | class Cat(Animal): 31 | 32 | def says(self): 33 | """return sound of cat 34 | :returns: "meow" 35 | 36 | """ 37 | return 'meow' 38 | -------------------------------------------------------------------------------- /mysite/zoo/tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | 5 | from django.test import TestCase 6 | 7 | from zoo import models 8 | 9 | 10 | class AnimalTestCase(TestCase): 11 | 12 | """Test animals' sound """ 13 | 14 | def test_dog_says(self): 15 | """test dog says woof or not 16 | 17 | """ 18 | dog = models.Dog(name='Snoopy') 19 | self.assertEqual(dog.says(), 'woof') 20 | 21 | def test_cat_says(self): 22 | """test cat says meow of not 23 | 24 | """ 25 | cat = models.Cat(name='Garfield') 26 | self.assertEqual(cat.says(), 'meow') 27 | -------------------------------------------------------------------------------- /mysite/zoo/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django>=1.8, <=1.9 2 | --------------------------------------------------------------------------------