Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django错误:AttributeError at/';GalleryListViewIndex';对象没有属性';META&x27;_Python_Django - Fatal编程技术网

Python Django错误:AttributeError at/';GalleryListViewIndex';对象没有属性';META&x27;

Python Django错误:AttributeError at/';GalleryListViewIndex';对象没有属性';META&x27;,python,django,Python,Django,我是Python和Django的初学者,我坚持自己的观点。当我尝试呈现请求时,出现以下错误:Django错误:AttributeError at/'GalleryListViewIndex'对象没有属性'META' 我不知道为什么我会这样,我搜索了一些答案并尝试了一些操作,但我所做的一切都不起作用 我正在使用photologue构建一个小的公文包应用程序,我正在尝试获取画廊的第一张图片,并将其显示在索引页上 以下是画廊和照片课程的模型: photologue.models.Gallery: cl

我是Python和Django的初学者,我坚持自己的观点。当我尝试呈现请求时,出现以下错误:Django错误:AttributeError at/'GalleryListViewIndex'对象没有属性'META'

我不知道为什么我会这样,我搜索了一些答案并尝试了一些操作,但我所做的一切都不起作用

我正在使用photologue构建一个小的公文包应用程序,我正在尝试获取画廊的第一张图片,并将其显示在索引页上

以下是画廊和照片课程的模型:

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
索引页的My 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'

我真的不明白为什么它会让我犯这个错误。任何帮助都将不胜感激

get\u queryset
有一个作业,并且只有一个作业,即获取一个queryset(因此而得名)

您当前拥有的其余逻辑可能属于
get\u context\u 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 = 'index.html'

好吧,渲染也没有采用那种方法。按照你所写的,我现在有一个错误:没有定义/name'self'处的NameError,但无论如何感谢你的时间:)@Lcab-修复,出于某种原因,我撤销了对上下文数据的一些编辑,(get_queryset也有错误,但最初不会导致任何错误)这是在/get_queryset()处引发TypeError,它接受1个位置参数,但给出了2个。。。。。我真的迷路了@Sayse-它有效!!!!!!!谢谢!我无法独自解决这个问题。。。!再次感谢!
template_name = 'index.html'