7 一个小案例

这是项目urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('booktest.urls'))
]

这是booktest应用中的urls.py

from django.contrib import admin
from django.urls import path,re_path
from booktest import views

urlpatterns = [
    path('index', views.index),
    path('book', views.book_show),
    re_path(r"book/(\d+)",views.detail)

]

 

这是models.py

 

from django.db import models

# Create your models here.
class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub = models.DateField()

    def __str__(self):
        return self.btitle


class HeroInfo(models.Model):
    hname = models.CharField(max_length=20)
    hgender = models.BooleanField(default=False)
    hcomment = models.CharField(max_length=100)
    hbook = models.ForeignKey('BookInfo', on_delete=models.CASCADE)

    def __str__(self):
        return self.hname

 

 

这是admin.py

 

from django.contrib import admin
from booktest.models import BookInfo,HeroInfo

class BookAdmin(admin.ModelAdmin):
    list_display = ['id','btitle','bpub']


class HeroAdmin(admin.ModelAdmin):
    list_display = ['id','hname','hgender','hcomment','hbook']


# Register your models here.
admin.site.register(BookInfo, BookAdmin)
admin.site.register(HeroInfo, HeroAdmin)

 

 

 

这是views.py

 

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from booktest.models import BookInfo

def index(request):
    pass

def book_show(request):
    booklist = BookInfo.objects.all()
    context = {'books':booklist}
    return render(request,'booktest/index.html', context)


def detail(request,b_id):
    book = BookInfo.objects.get(id=b_id)
    hero = book.heroinfo_set.all()
    return render(request,'booktest/detail.html',{'book':book,"hero":hero})

 

这是index.html模版

<!DOCTYPE html>
<html>
<head>
    <title>模版文件</title>
</head>
<body>
<h1>这是一个模版文件</h1>
<!-- 使用模版变量 -->
图书列表:
<ul>
    {% for book in books %}

    <li><a href="/book/{{book.id}}">{{book}}</a></li>

    {% endfor %}
</ul>
</body>
</html>

 

这是detail.html模版

 

<!DOCTYPE html>
<html>
<head>
    <title>显示图书关联的英雄信息</title>
</head>
<body>
    <h1>{{ book.btitle }}</h1><br>
    <h2>英雄信息如下:</h2><br>
    <ul>
    {% for i in hero %}
    <li>{{ i.hname }}-----{{ i.hcomment }}</li>
    {% empty %}
    <li>没有英雄信息</li>
    {% endfor %}
    </ul>

</body>
</html>

 

posted @ 2019-07-30 23:38  greenfan  阅读(277)  评论(0)    收藏  举报