django 編寫資料介面

如果❤️我的文章有幫助,歡迎點贊、關注。這是對我繼續技術創作最大的鼓勵。

更多系列文章在我部落格[1]

django 編寫資料介面

django-admin

•django-shell 新增文章太複雜•建立管理員使用者•登陸頁面進行管理

建立超級使用者

python manage。py createsuperuser

訪問:http://127。0。0。1:8000/admin/ admin / 1234qwer

註冊文章管理 到管理後臺

blog\admin。py

from django。contrib import admin# Register your models here。from 。models import Articleadmin。site。register(Article)

希望在列表 看到 文章標題

blog\models。py

# Create your models here。class Article(models。Model): article_id = models。AutoField(primary_key=True) title = models。TextField() brief_content = models。TextField() content = models。TextField() publish_date = models。DateTimeField(auto_now=True) def __str__(self): return self。title

介面獲取文章資料

獲取請求引數

# get# 在專案下的urls。py下增加設定:url(r‘^user/$’,views。index)# 在user。views的index檢視中:def index(request): id = request。GET。get(“id”) pid = request。GET。get(“pid”) return HttpResponse(“獲得資料 %s %s”%(id,pid))# post def index(request): id = request。POST。get(“id”) pid = request。POST。get(“pid”) return HttpResponse(“獲得資料 %s %s”%(id,pid))

獲取文章內容

def article_content(request): id = request。GET。get(“id”) art = Article。objects。all()[int(id)] return_str = ‘article_id: %s,title: %s,brief_content: %s,content: %s,publish_date: %s’ % ( art。article_id, art。title, art。brief_content, art。content, art。publish_date ) return HttpResponse(return_str)

django 模板引擎

模板變數標籤:{{ now }} 迴圈標籤:{% for x in list %}, {% endfor %} 判斷標籤:{% if %}, {% elseif %}, {% endif %}

新增頁面,渲染頁面

•新增 blog\templates\blog\article_list。html•blog\views。py 新增 頁面渲染方法

def get_index_page(request):all_article = Article。objects。all()

blog\templates\blog\article_detail。html

return render(request, ‘blog/article_list。html’, {‘article_list’:all_article})

- blog\urls。py 新增url```pythonfrom django。urls import path, includeimport blog。viewsurlpatterns = [ path(‘hello_world’,blog。views。hello_world), path(r‘article’,blog。views。article_content), path(r‘index’,blog。views。get_index_page),]

模型搜尋介紹

模型的查詢 會建立 QuerySet 是惰性且唯一的

•all() 返回的 QuerySet 包含了資料表中所有的物件。•get() 檢索單個物件

鏈式過濾器

Entry。objects。filter( headline__startswith=‘What’)。exclude( pub_date__gte=datetime。date。today())。filter( pub_date__gte=datetime。date(2005, 1, 30))

條數限制

這會返回第 6 至第 10 個物件 (OFFSET 5 LIMIT 5):

Entry。objects。order_by(‘headline’)。all()[5:10]

•exact 匹配 iexact 大小寫不敏感 Entry。objects。get(headline__exact=“Cat bites dog”) # SELECT 。。。 WHERE headline = ‘Cat bites dog’;•contains 包含 大小寫敏感 Entry。objects。get(headline__contains=‘Lennon’) # SELECT 。。。 WHERE headline LIKE ‘%Lennon%’;•in Entry。objects。filter(id__in=[1, 3, 4])

配置靜態資源

檔案存放

靜態檔案放在對應的 app 下的 static 資料夾中 或者 STATICFILES_DIRS 中的資料夾中。

measure/settings。py 配置

DEBUG=TrueSTATIC_URL = ‘/static/’# 當執行 python manage。py collectstatic 的時候# STATIC_ROOT 資料夾 是用來將所有STATICFILES_DIRS中所有資料夾中的檔案,以及各app中static中的檔案都複製過來# 把這些檔案放到一起是為了用apache等部署的時候更方便STATIC_ROOT = os。path。join(BASE_DIR, ‘collected_static’)# 其它 存放靜態檔案的資料夾,可以用來存放專案中公用的靜態檔案,裡面不能包含 STATIC_ROOT# 如果不想用 STATICFILES_DIRS 可以不用,都放在 app 裡的 static 中也可以STATICFILES_DIRS = ( os。path。join(BASE_DIR, “common_static”), ‘/path/to/others/static/’, # 用不到的時候可以不寫這一行)# 這個是預設設定,Django 預設會在 STATICFILES_DIRS中的資料夾 和 各app下的static資料夾中找檔案# 注意有先後順序,找到了就不再繼續找了STATICFILES_FINDERS = ( “django。contrib。staticfiles。finders。FileSystemFinder”, “django。contrib。staticfiles。finders。AppDirectoriesFinder”)

部署

python manage。py collectstatic

nginx 配置

location /media { alias /path/to/project/media;}location /static { alias /path/to/project/collected_static;}

References

[1] 更多系列文章在我部落格:

https://coderdao。github。io/