我是 Django 新手,正在尝试制作一个基本网站,但在获取页面的相关记录时遇到了一些困难。
模型.py
import datetime
from django.db import models
from django.conf import settings
from ckeditor.fields import RichTextField
from markdown import markdown
class LiveEntryManager(models.Manager):
def get_query_set(self):
return super(LiveEntryManager,self).get_query_set().filter(status=self.model.LIVE_STATUS)
class Page(models.Model):
LIVE_STATUS = 1
HIDDEN_STATUS = 2
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(HIDDEN_STATUS, 'Hidden'),
)
title = models.CharField(max_length=250, help_text='Max 250 characters.')
slug = models.SlugField(unique=True, help_text='Suggested automatically generated from the title. Must be unique')
description = RichTextField()
description_html = models.TextField(editable=False, blank=True)
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS,
help_text="Only pages with live status will be publicly displayed")
def save(self, force_insert=False, force_update=False):
self.description_html = markdown(self.description)
super(Page, self).save(force_insert, force_update)
def get_record(self):
return self.objects.get()
#Managers
live = LiveEntryManager()
objects = models.Manager()
class Meta:
ordering = ['title']
verbose_name_plural = "Pages"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/%s/" % self.slug
class Image(models.Model):
page = models.ForeignKey(Page)
name = models.CharField(max_length=250)
image = models.ImageField(upload_to='gallery')
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
和 Views.py
from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic.list_detail import object_list
from mainsite.models import Page, Image
def home(request):
return render_to_response('templates/home.html')
def page(request, slug):
one_page = get_object_or_404(Page, slug=slug)
return render_to_response('templates/page/page.html',
{ 'object_list': one_page.get_record() })
和 Urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mainsite.views.home', name='home'),
# url(r'^disability/', include('disability.foo.urls')),
url(r'^page/(?P<slug>[-\w]+)/$', 'mainsite.views.page'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^grappelli/', include('grappelli.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
我想要做的是能够说 /page/test 并仅获取该对象的标题、描述和图像。我知道如何获取所有对象并将它们显示在模板中,但不知道如何获取单个记录,并且会感谢一些帮助。
谢谢