我是Python和Django的初学者,我坚持自己的观点。当我尝试呈现请求时出现以下错误:Django错误:/'GalleryListViewIndex'对象中的AttributeError没有属性'META'。
我不知道为什么我会这样做,我搜索了一些答案并尝试了一些操作,但我所做的一切都没有用。
我正在使用photologue构建一个小型投资组合应用程序,我正在尝试获取图库的第一张图片,以便在索引页面上显示它。
以下是Gallery和Photo类的模型:
photologue.models.Gallery:
class Gallery(models.Model):
date_added = models.DateTimeField(_('date published'),
default=now)
title = models.CharField(_('title'),
max_length=250,
unique=True)
slug = models.SlugField(_('title slug'),
unique=True,
max_length=250,
help_text=_('A "slug" is a unique URL-friendly title for an object.'))
description = models.TextField(_('description'),
blank=True)
is_public = models.BooleanField(_('is public'),
default=True,
help_text=_('Public galleries will be displayed '
'in the default views.'))
photos = SortedManyToManyField('Photo',
related_name='galleries',
verbose_name=_('photos'),
blank=True)
sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
blank=True)
objects = GalleryQuerySet.as_manager()
class Meta:
ordering = ['-date_added']
get_latest_by = 'date_added'
verbose_name = _('gallery')
verbose_name_plural = _('galleries')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('photologue:pl-gallery', args=[self.slug])
def latest(self, limit=LATEST_LIMIT, public=True):
if not limit:
limit = self.photo_count()
if public:
return self.public()[:limit]
else:
return self.photos.filter(sites__id=settings.SITE_ID)[:limit]
def sample(self, count=None, public=True):
"""Return a sample of photos, ordered at random.
If the 'count' is not specified, it will return a number of photos
limited by the GALLERY_SAMPLE_SIZE setting.
"""
if not count:
count = SAMPLE_SIZE
if count > self.photo_count():
count = self.photo_count()
if public:
photo_set = self.public()
else:
photo_set = self.photos.filter(sites__id=settings.SITE_ID)
return random.sample(set(photo_set), count)
def photo_count(self, public=True):
"""Return a count of all the photos in this gallery."""
if public:
return self.public().count()
else:
return self.photos.filter(sites__id=settings.SITE_ID).count()
photo_count.short_description = _('count')
def public(self):
"""Return a queryset of all the public photos in this gallery."""
return self.photos.is_public().filter(sites__id=settings.SITE_ID)
def orphaned_photos(self):
"""
Return all photos that belong to this gallery but don't share the
gallery's site.
"""
return self.photos.filter(is_public=True)\
.exclude(sites__id__in=self.sites.all())
photologue.models.Photos:
class Photo(ImageModel):
title = models.CharField(_('title'),
max_length=250,
unique=True)
slug = models.SlugField(_('slug'),
unique=True,
max_length=250,
help_text=_('A "slug" is a unique URL-friendly title for an object.'))
caption = models.TextField(_('caption'),
blank=True)
date_added = models.DateTimeField(_('date added'),
default=now)
is_public = models.BooleanField(_('is public'),
default=True,
help_text=_('Public photographs will be displayed in the default views.'))
sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
blank=True)
objects = PhotoQuerySet.as_manager()
class Meta:
ordering = ['-date_added']
get_latest_by = 'date_added'
verbose_name = _("photo")
verbose_name_plural = _("photos")
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if self.slug is None:
self.slug = slugify(self.title)
super(Photo, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('photologue:pl-photo', args=[self.slug])
def public_galleries(self):
"""Return the public galleries to which this photo belongs."""
return self.galleries.filter(is_public=True)
def get_previous_in_gallery(self, gallery):
"""Find the neighbour of this photo in the supplied gallery.
We assume that the gallery and all its photos are on the same site.
"""
if not self.is_public:
raise ValueError('Cannot determine neighbours of a non-public photo.')
photos = gallery.photos.is_public()
if self not in photos:
raise ValueError('Photo does not belong to gallery.')
previous = None
for photo in photos:
if photo == self:
return previous
previous = photo
def get_next_in_gallery(self, gallery):
"""Find the neighbour of this photo in the supplied gallery.
We assume that the gallery and all its photos are on the same site.
"""
if not self.is_public:
raise ValueError('Cannot determine neighbours of a non-public photo.')
photos = gallery.photos.is_public()
if self not in photos:
raise ValueError('Photo does not belong to gallery.')
matched = False
for photo in photos:
if matched:
return photo
if photo == self:
matched = True
return None
索引页面的我的views.py:
class GalleryListViewIndex(ListView):
paginate_by = 20
def get_queryset(request):
x = []
queryset = Gallery.objects.on_site().is_public()[:4]
for g in queryset:
r = [g.photos.first()]
x += r
first_pic = x
return render(request,'index.html', context={'first_pic': first_pic})
这是我正在拍摄4幅画廊的第一张照片。
这是错误的追溯:
Traceback:
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/views/generic/list.py" in get
159. self.object_list = self.get_queryset()
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/photologue/views.py" in get_queryset
35. return render(request,'index.html', context={'first_pic': first_pic})
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/loader.py" in render_to_string
97. return template.render(context, request)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/base.py" in render
204. with context.bind_template(self):
File "/usr/lib/python3.4/contextlib.py" in __enter__
59. return next(self.gen)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
79. context = processor(self.request)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/context_processors.py" in debug
41. if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
Exception Type: AttributeError at /
Exception Value: 'GalleryListViewIndex' object has no attribute 'META'
我真的不明白为什么它会引起我这个错误。任何帮助将非常感激...!
答案 0 :(得分:1)
get_queryset
只有一个作业和一个作业,即获取一个查询集(因此得名)
def get_queryset(self):
return Gallery.objects.on_site().is_public()[:4]
您目前拥有的其余逻辑可能属于get_context_data
def get_context_data(self, *args, **kwargs):
context = super(GalleryListViewIndex, self).get_context_data(*args, **kwargs)
x = []
for g in self.get_queryset():
r = [g.photos.first()]
x += r
first_pic = x
context['first_pic'] = first_pic
return context
然后,只需设置template_name
template_name = 'index.html'