0

抱歉,如果这是一种愚蠢的提问方式...我有一个网站主页的通用列表视图,并且想在同一页面上使用“主页”模型来获取信息性文本...这可能吗?谢谢你的帮助。

模型.py

from django.db import models


class School(models.Model):
    school_name = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.school_name

def get_absolute_url(self):
        return "/schools/%s/" % self.slug

class Student(models.Model):
    name = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    slug = models.SlugField(unique=True)
    mugshot = models.ImageField(upload_to='mugshots')
    school = models.ForeignKey(School)  
    honor = models.TextField()

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return "/student/%s/" % self.slug

class Homepage(models.Model):
    title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    content = models.TextField() 

    def __unicode__(self):
        return self.title

网址.py

from django.conf.urls.defaults import *
from achievers.apps.students.models import School, Student
from achievers.apps.students.views import hello

from django.contrib import admin
admin.autodiscover()

info_dict = {
    'queryset': School.objects.all(),
    'extra_context': {'school_list': School.objects.all,}    
}

info_dict2 = {
    'queryset': Student.objects.all(),
    'template_name': 'students/student_detail.html',
    'extra_context': {'student_detail': Student.objects.all}    
}

urlpatterns = patterns('',
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static'}),
    (r'^student/(?P<slug>[-\w]+)/$', 'django.views.generic.list_detail.object_detail', info_dict2), 
    (r'^students/(?P<slug>[-\w]+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
    (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
    (r'^admin/', include(admin.site.urls)),
    (r'^hello/', hello),
)
4

1 回答 1

1

当您说您想将主页模型与通用列表视图“使用”时,我不确定您的意思。如果您只想访问 的所有实例Homepage,您可以在 urls.py 中将以下内容添加到 info_dict:

info_dict = {
    'queryset' : School.objects.all(),
    'extra_context' : {'school_list' : School.objects.all(), 'homepage_list' : Homepage.objects.all()}
}

如果要将特定实例传递Homepage给通用视图,可以使用类似的技术:

...
'extra_context' : {'school_list' : School.objects.all(), 'homepage' : Homepage.objects.filter(id = 1).get()}

最后,如果您想要更复杂的东西(例如id在过滤器上使用动态),您始终可以定义一个自定义视图,然后object_list从该视图中调用,例如:

def my_view(request, dynamic_id):
    info_dict = {..., 'extra_context' : {..., 'homepage' : Homepage.objects.filter(id = dynamic_id).get()}}
    return django.views.generic.list_detail.object_list(**info_dict)
于 2010-02-16T07:49:48.383 回答