0

我是 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 并仅获取该对象的标题、描述和图像。我知道如何获取所有对象并将它们显示在模板中,但不知道如何获取单个记录,并且会感谢一些帮助。

谢谢

4

2 回答 2

1

如果您想在数据库中查询单个 Page 模型,您可以使用

views.py

from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse 
from models import Pages



def page(request, slug):
    try:
        page = Pages.objects.get(slug=slug)
    except ObjectDoesNotExist:
        return HttpResponse(status=404)
    return render(request, 'templates/page/page.html', {'page': page})

然后只需使用

{{page.title}}

或模板中的类似内容。

此外,如果您想查询并返回一个可迭代的列表,您可以使用

Pages.objects.filter()

代替

Pages.objects.get()
于 2017-03-31T14:47:36.513 回答
0

你从哪里来get_record()的?的返回值get_object_or_404是一个模型实例。没有什么可以“获取”的,只需将实例传递给您的上下文即可。并且,不要object_list用作上下文名称。这不仅是一个实例,而不是列表或查询集,而且该名称最常与分页一起使用,如果您实际上没有对任何内容进行分页,您只会在代码中造成混乱。

return render_to_response('templates/page/page.html', {
    'one_page': one_page,
})

然后在您的模板中:

<h1>{{ one_page.title }}</h1>
<img src="{{ one_page.image.url }}" alt="">
<p>{{ one_page.description }}</p>
于 2012-09-24T21:07:43.167 回答