抱歉,我是 Django 和一般编程的新手,但我试图从我的模型中调用变量以显示在特定页面上。我将我的 URL 映射到 example.com/archive/book_slug 并想要标题、作者、ISBN 等详细信息。我使用博客应用程序在管理页面中注册我的模型。
当我转到 URL 时,我的模板中出现了问题,没有显示任何内容。我希望书名出现在标题中。有人可以帮忙吗?
博客/models.py
from django.db import models
class Book_item(models.Model):
book_title = models.CharField(max_length=255, blank=False)
book_author = models.CharField(max_length=255)
book_publisher = models.CharField(max_length=255, blank=True)
book_date_published = models.IntegerField(blank=True)
book_isbn = models.IntegerField(blank=True)
book_slug = models.SlugField(max_length=255, unique=True, blank=False,
primary_key=True)
book_body = models.TextField(blank=True)
def __unicode__(self):
return self.book_title
博客/views.py
from django.shortcuts import render, get_object_or_404
from blog.models import Book_item
# view for /achive/; template at archive.html
def archive_index(request):
book_info = Book_item.objects.all()
context = {'book_info' : book_info}
return render(request, 'blog/archive.html', context)
# view for /archive/book_title; 404 if no title; template at book_detail.html
def book_details(request, book_slug):
bookdeets = Book_item.objects.filter(book_slug=book_slug)
details = get_object_or_404(Book_item, book_slug=book_slug)
context = {'details' : details, 'bookdeets' : bookdeets}
return render(request, 'blog/book_detail.html', context)
博客/urls.py
from django.conf.urls import patterns, url
from blog import views
urlpatterns = patterns('',
# archive index at /archive/
url(r'^$', views.archive_index),
# book deatils at /archive/book_title
url(r'^(?P<book_slug>[\w-]+)/$', views.book_details),
)
博客/book_detail.html
{% extends "base.html" %}
{% block title %}{{Book_item.book_title}}{% endblock %}
{% block headercontent %}
<h1>{{Book_item.book_title}}</h1>
{% endblock %}