后台关联添加
关联对象
- 对于HeroInfo模型类,有两种注册方式
-方式一:与BookInfo模型类相同
-方式二:关联注册
- 按照BookInfor的注册方式完成HeroInfo的注册
- 接下来实现关联注册
修改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)
效果图:
可以将内嵌的方式改为表格
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中,视图对WEB请求进行回应
- 视图接收reqeust对象作为第一个参数,包含了请求的信息
- 视图就是一个Python函数,被定义在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,否则无法处理请求
URLconf
- 在Django中,定义URLconf包括正则表达式、视图两部分
- Django使用正则表达式匹配请求的URL,一旦匹配成功,则调用应用的视图
- 注意:只匹配路径部分,即除去域名、参数后的字符串
- 在test1/urls.py插入booktest,使主urlconf连接到booktest.urls模块
在booktest下新建一个urls.py文件,然后添加以下代码:
#coding:utf-8
from django.conf.urls import url
from . import views
# url(r'^index$',views.index) 对照效果图看区别
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)
效果图: