0
大家好,我在这个问题上苦苦挣扎,谷歌搜索了这个硬核。Django:用ManyToManyField循环遍历两个for循环
我正在开发一个图像库,每个相册输出,当点击一个屏幕覆盖显示图像库。艰苦的工作已经在JavaScript中已经完成了在画廊中显示的每个图像,所以我只需要由给定的图像路径:
{{ images.content }}
下面是我的文件,我用我的Django项目。
对此的帮助将会很棒。
manage.py
from django.db import models
PHOTO_PATH = 'media_gallery'
class Gallerys(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
slug = models.SlugField(unique_for_date='date', help_text='This is automatic, used in the URL.')
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Image Galleries"
ordering = ('-date',)
def __unicode__(self):
return self.title
class Images(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
content = models.FileField(upload_to=PHOTO_PATH,blank=False, help_text='Ensure the image size is small and it\'s aspect ratio is 16:9.')
gallery = models.ManyToManyField(Gallerys)
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Images"
ordering = ('-date',)
def __unicode__(self):
return self.title
import models
from django.contrib import admin
class ImagesAdmin(admin.ModelAdmin):
list_display = ('title', 'date')
class GallerysAdmin(admin.ModelAdmin):
list_display = ('title', 'date', 'slug')
admin.site.register(models.Images, ImagesAdmin)
admin.site.register(models.Gallerys,GallerysAdmin)
views.py
from django.http import HttpResponse
from notices.models import Notices
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response
from gallery.models import *
from navigation.models import *
# when the galleries page is requested, all image galleries are listed by date created with the latest first,
# each gallery displayed contains a javascript tag containing an index of images separated by ';'
def galleries(request):
gallery = Gallerys.objects.all()
images = Images.objects.all()
return render_to_response('galleries.html', {'Galleries': gallery, 'Images': images})
galleries.html
{% for galleries in Galleries %}
<h1>{{ galleries.title }}</h1>
{% for images in galleries.gallery.all %}
<h2>{{ images.content }}</h2>
{% empty %}
none
{% endfor %}
{% endfor %}
当我通过迭代:
<h2>{{ images.content }}</h2>
我什么也没得到,我哪里出错了?
谢谢!
感谢虞姬,你的建议的工作,立竿见影! –