2 Django應用 第1部分
阿新 • • 發佈:2017-10-22
入口 ews font 字段 cfile pre 添加 顯示 htm
目標應用:
- 一個公開的網站,可以讓訪客查看投票的結果並讓他們進行投票。
- 一個後臺管理網站,你可以添加、修改和刪除選票。
查看django版本
python -c "import django; print(django.get_version())"
2.1創建一個項目
django-admin startproject mysite
mange.py:命令行工具
mysite/:項目的真正python包,導入時需要使用python包名字,如mysite.urls
mysite/setting.py:Django項目的配置
mysite/urls.py:Django站點的目錄
mysite/wsgi.py:用於項目的WSGI兼容的Web服務器入口
2.2數據庫的建立
默認數據庫使用SQLite,在setting.py文件的DATABASES‘default’中,可以修改數據庫設置。ENGINE為支持的數據庫,NAME為數據庫名稱,默認為os.path.join(BASE_DIR, ‘db.sqlite3‘)
python manage.py migrate 根據數據庫設置自動創建數據庫表
python manage.py runserver 啟動Django開發服務器,默認端口8000
python manage.py runserver 8080 使用8080端口
python manage.py runserver 0.0.0.0:8000 其他電腦上展示
2.3創建模型
項目:項目是一個特定網站中相關配置和應用的集合。
應用:應用是一個Web應用程序,它完成具體的事項——比如一個博客系統、一個存儲公共檔案的數據庫或者一個簡單的投票應用。可以運用於多個項目。
開發環境建立後,使用python manage.py startapp polls創建應用。
結構如下polls/ __init__.py admin.py migrations/ __init__.py models.py tests.py views.py
當編寫一個數據庫驅動的Web應用時,第一步就是定義該應用的模型 —— 本質上,就是定義該模型所對應的數據庫設計及其附帶的元數據。
這個簡單的投票應用中,我們將創建兩個模型: Question和Choice。
polls/models.py from django.db import models #通過Field類的實例表示字段,告訴Django,每個字段中保存著什麽類型的數據。 class Question(models.Model): question_text = models.CharField(max_length=200)#字符字段 pub_date = models.DateTimeField(‘date published‘)#日期字段 class Choice(models.Model): question = models.ForeignKey(Question) #ForeignKey定義了一個關聯。它告訴Django每個Choice都只關聯一個Question choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
2.4激活模型
第一步.告訴項目polls應用安裝
再次編輯mysite/settings.py文件,並修改INSTALLED_APPS設置以包含字符串‘polls‘。所以它現在是這樣的:
mysite/settings.py INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘polls‘, )
第二步.為應用創建數據庫表
python manage.py makemigrations polls為這些修改創建遷移文件
python manage.py migrate將這些改變更新到數據庫中。
2.5玩轉API
先修改models.py,添加__str__()方法給Question和Choice,不僅會使你自己在使用交互式命令行時看得更加方便,而且會在Django自動生成的管理界面中使用對象的這種表示。
polls/models.py from django.db import models class Question(models.Model): # ... def __str__(self): r return self.question_text class Choice(models.Model): # ... def __str__(self): return self.choice_text
python manage.py shell
進入python環境,;路徑為mysite/setting.py文件的路徑
>>> from polls.models import Question, Choice # 導入剛寫的模型 # 查看所有對象 >>> Question.objects.all() [] #使用timezone代替datetime.now()防止出錯 >>> from django.utils import timezone >>> q = Question(question_text="What‘s new?", pub_date=timezone.now()) #保存對象 >>> q.save() >>> q.id 1 #查看屬性 >>> q.question_text "What‘s new?" >>> q.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # 改變屬性 >>> q.question_text = "What‘s up?" >>> q.save() # 查看所有對象 >>> Question.objects.all() [<Question: Question object>]
添加一個自定義方法
polls/models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
保存這些改動,然後通過python manage.py shell再次打開一個新的Python 交互式shell:
>>> from polls.models import Question, Choice >>> Question.objects.all() [<Question: What‘s up?>] # Django提供了一個豐富的數據庫查找API,通過關鍵字查找。 >>> Question.objects.filter(id=1) [<Question: What‘s up?>] >>> Question.objects.filter(question_text__startswith=‘What‘) [<Question: What‘s up?>] # 獲取與今年年份相等的對象 >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: What‘s up?> # 如果ID不存在,報錯 >>> Question.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Question matching query does not exist. # 由主鍵查找是最常見的情況,因此Django提供了一種對主鍵精確查找的快捷方式。下面的內容與問題.objects.get(id=1)相同。 >>> Question.objects.get(pk=1) <Question: What‘s up?> # 查看定義的方法是否可用 >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True # 顯示所有相關對象集 >>> q.choice_set.all() [] # 用create創建新對象. >>> q.choice_set.create(choice_text=‘Not much‘, votes=0) <Choice: Not much> >>> q.choice_set.create(choice_text=‘The sky‘, votes=0) <Choice: The sky> >>> c = q.choice_set.create(choice_text=‘Just hacking again‘, votes=0) # 通過API訪問關聯的對象 >>> c.question <Question: What‘s up?> # 反之也成立 >>> q.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> q.choice_set.count() 3 # 選擇查看對象 >>> Choice.objects.filter(question__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # 刪除對象 >>> c = q.choice_set.filter(choice_text__startswith=‘Just hacking‘) >>> c.delete()
2 Django應用 第1部分