抱歉,我是Django的新手并且一般编程,但我正在尝试调用我的模型中的变量以显示在特定页面上。我将我的网址映射到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 %}
答案 0 :(得分:3)
尝试;
<h1>{{details.book_title}}</h1>
您已通过响应上下文中的“details”变量将书籍详细信息传递给模板。
另外,您实际上也可以删除bookdeets = Book_item.objects.filter(book_slug=book_slug)
行,因为您已经通过下面的get_object_or_404方法直接获得了所需的书。鉴于slug是唯一的,filter
将返回单个元素查询集,因此这些只是两种不同的方式来获取相同的对象(除了get_object_or_404是一个方便的'快捷方式',如果找不到任何内容将返回404)
答案 1 :(得分:0)
尝试使用小写的模型名称。
<h1>{{ book_item.book_title }}</h1>