【发布时间】:2021-12-20 22:17:59
【问题描述】:
我正在尝试构建一个简单的 Django 画廊,允许将照片添加到相册中。到目前为止一切正常(上传照片、添加到相册、对所有照片列表进行分页、照片详细信息/显示页面等),直到我尝试显示“相册”页面。我可以让页面呈现相册和所有相关照片,但如果我尝试对相册进行分页,事情就会变得很奇怪。
这是我的模型:
# models.py
class Albums(models.Model):
id = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=500)
slug = models.SlugField(max_length=500, unique=True)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
return super().save(*args, **kwargs)
class Photos(models.Model):
id = models.AutoField(primary_key=True, unique=True)
album = models.ForeignKey(
Albums, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Album"
)
photo = models.ImageField(upload_to="photos/")
slug = models.CharField(max_length=16, null=False, editable=False) # I know I'm not using a SlugField here; that's on purpose
title = models.CharField(max_length=500)
description = models.TextField(blank=True, null=True)
upload_date = models.DateTimeField(
default=timezone.now, verbose_name="Date uploaded"
)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
[...] # stuff to get the image's EXIF data and use that to set the slug
self.slug = str(datetime.strftime(img_date, "%Y%m%d%H%M%S"))
[...] # plus a bunch of other stuff that happens on save, not important here
super(Photos, self).save()
def delete(self, *args, **kwargs):
[...] # a bunch of stuff that happens on delete, not important here
super(Photos, self).delete()
还有让我痛苦的观点:
# views.py
class PhotoAlbum(DetailView):
context_object_name = "album"
model = Albums
slug_field = "slug"
template_name = "page.html"
def get_photos(self, **kwargs):
# get the integer id of the album
a = Albums.objects.filter(slug=self.kwargs["slug"])
a_id = a.values()[0]["id"]
# get the list go photos in that album
photos = Photos.objects.all().order_by("-capture_date").filter(album_id=a_id)
return photos
def get_context_data(self, **kwargs):
context = super(PhotoAlbum, self).get_context_data(**kwargs)
context["photos"] = self.get_photos()
return context
这些在基本模板中工作...
# album.html
<h2>{{ album.name }}</h2>
<p>{{ album.description }}</p>
<ul>
{% for photo in photos %}
<li><a href="{% url 'photo_detail' photo.slug %}">{{ photo.title }}</a></li>
{% endfor %}
</ul>
...但是如果我尝试通过更改对照片进行分页...
photos = Photos.objects.all().order_by("-capture_date").filter(album_id=a_id)
...到...
photos = Paginator(Photos.objects.all().order_by("-capture_date").filter(album_id=a_id), 10)
...我什么也得不到。
在四处搜索时,我看到的几乎所有与分页有关的问题都是针对 DRF 的,所以在这里碰壁了。我在显示照片与相册的关系时遇到了各种麻烦(get_photos() 函数),所以我猜测我的部分问题在于。有关如何使其正常工作的任何建议?
【问题讨论】:
标签: django django-models django-views django-orm django-pagination