后臺(tái)關(guān)聯(lián)添加
關(guān)聯(lián)對(duì)象
- 對(duì)于HeroInfo模型類僧免,有兩種注冊(cè)方式
-方式一:與BookInfo模型類相同
-方式二:關(guān)聯(lián)注冊(cè) - 按照BookInfor的注冊(cè)方式完成HeroInfo的注冊(cè)
- 接下來實(shí)現(xiàn)關(guān)聯(lián)注冊(cè)
修改admin.py
from django.contrib import admin
from models import *
# Register your models here.
class HeroInfoInline(admin.StackedInline):
model = HeroInfo
extra = 3
class BookInfoAdmin(admin.ModelAdmin):
list_display = ['id','btitle','bpub_date']
list_filter = ['btitle']
search_fields = ['btitle']
list_per_page = 1
fieldsets = [
('base',{'fields':['btitle']}),
('super',{'fields':['bpub_date']})
]
inlines = [HeroInfoInline]
admin.site.register(BookInfo,BookInfoAdmin)
admin.site.register(HeroInfo)
效果圖:
-
可以將內(nèi)嵌的方式改為表格
class HeroInfoInline(admin.TabularInline)
- 修改admin.py
from django.contrib import admin
from models import *
# Register your models here.
class HeroInfoInline(admin.TabularInline):
model = HeroInfo
extra = 3
class BookInfoAdmin(admin.ModelAdmin):
list_display = ['id','btitle','bpub_date']
list_filter = ['btitle']
search_fields = ['btitle']
list_per_page = 10
fieldsets = [
('base',{'fields':['btitle']}),
('super',{'fields':['bpub_date']})
]
inlines = [HeroInfoInline]
admin.site.register(BookInfo,BookInfoAdmin)
admin.site.register(HeroInfo)
效果圖:
視圖(views.py)
- 在django中嫡秕,視圖對(duì)WEB請(qǐng)求進(jìn)行回應(yīng)
- 視圖接收reqeust對(duì)象作為第一個(gè)參數(shù),包含了請(qǐng)求的信息
- 視圖就是一個(gè)Python函數(shù)福扬,被定義在views.py中
#coding:utf-8
# from django.shortcuts import render
from django.http import *
# Create your views here.
def index(request):
return HttpResponse('hello world')
- 定義完成視圖后,需要配置urlconf惜犀,否則無法處理請(qǐng)求
URLconf
- 在Django中铛碑,定義URLconf包括正則表達(dá)式、視圖兩部分
- Django使用正則表達(dá)式匹配請(qǐng)求的URL向拆,一旦匹配成功亚茬,則調(diào)用應(yīng)用的視圖
- 注意:只匹配路徑部分,即除去域名浓恳、參數(shù)后的字符串
- 在test1/urls.py插入booktest刹缝,使主urlconf連接到booktest.urls模塊
在booktest下新建一個(gè)urls.py文件,然后添加以下代碼:
#coding:utf-8
from django.conf.urls import url
from . import views
# url(r'^index$',views.index) 對(duì)照效果圖看區(qū)別
urlpatterns=[
url(r'^$',views.index)
]
coding:utf-8
在test1下urls.py文件,然后添加以下代碼:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^',include('booktest.urls'))
]
(python manage.py runserver)
效果圖: