在Django模板中通过Item.objects.all显示图像

发布于 2024-11-03 12:21:21 字数 2485 浏览 4 评论 0原文

在我的 index.html 中,我尝试通过对添加的日期进行排序来获取最新的 10 期(漫画书),然后通过如下表格显示这些问题的封面图像: http://www.comicbookresources.com/previews

Models.py:

class Image(models.Model):
    CATEGORY_CHOICES = (
    ('Cover', 'Cover'),    
    ('Scan', 'Scan'),
    ('Other', 'Other'),
    )
    title = models.CharField(max_length=256)
    image = models.ImageField(upload_to="images/")
    category = models.CharField(max_length=10, choices=CATEGORY_CHOICES)
    contributor = models.ManyToManyField(Contributor, blank=True, null=True)
    date_added = models.DateField(auto_now_add=True)    
    def __unicode__(self):
        return self.title
    class Meta:
        ordering = ['title']        

class Issue(models.Model):

    title = models.ForeignKey(Title)
    number = models.IntegerField(help_text="Do not include the '#'.")

    ....

    date_added = models.DateTimeField(auto_now_add=True)
    images = models.ManyToManyField(Image, related_name="images_inc", blank=True, null=True)

    ....


    def __unicode__(self):
        return u'%s #%s' % (self.title, self.number)
    def get_absolute_url(self):
        return "/issues/%s" % self.slug     
    class Meta:
        ordering = ['-date_added']

Views.py

def index(request):
    ....

    all_characters = Character.objects.all().filter(is_featured=True).order_by('name')
    latest_issues = Issue.objects.order_by('-date_added')[:10]

    ....

    t = loader.get_template('comics/index.html')
    c = Context({
        'all_characters': all_characters,
        'latest_issues': latest_issues,
       })
    return HttpResponse(t.render(c))

现在,这是我的 index.html 文件的设置方式:

{% for issue in latest_issues %} 
<li class="gallery">
<a href="{{ issue.get_absolute_url }}">
<img alt="{{ issue.title }} #{{ issue.number }}" title="{{ issue.title }} #{{ issue.number }}" src="{{ issue.images }}"></a>
<em>{{ issue.title }} #{{ issue.number }}</em>
</li>
{% endfor %}

< code>{{ issues.images }} 显示 ManyToManyDBManagex34982423 内容之一,{{ issues.images.all }} 显示类似“Image: Astonishing X-Men 1 Cover A”的内容而 {{ issues.images.url }} 则不显示任何内容。

我需要它来显示封面图像,更具体地说,我需要它显示一张被分类为“封面”的图像,因为有时会有不同的封面,我不希望它显示一期的两个封面。我确信我必须修复我的views.py,但是我将如何执行此操作,然后如何在我的模板中显示它?

宝贝说话。我对此很陌生。谢谢!

In my index.html, I am trying to grab the 10 latest (comic book) issues by sorting through date added and then having the cover image of those issues on display through a table like this: http://www.comicbookresources.com/previews

Models.py:

class Image(models.Model):
    CATEGORY_CHOICES = (
    ('Cover', 'Cover'),    
    ('Scan', 'Scan'),
    ('Other', 'Other'),
    )
    title = models.CharField(max_length=256)
    image = models.ImageField(upload_to="images/")
    category = models.CharField(max_length=10, choices=CATEGORY_CHOICES)
    contributor = models.ManyToManyField(Contributor, blank=True, null=True)
    date_added = models.DateField(auto_now_add=True)    
    def __unicode__(self):
        return self.title
    class Meta:
        ordering = ['title']        

class Issue(models.Model):

    title = models.ForeignKey(Title)
    number = models.IntegerField(help_text="Do not include the '#'.")

    ....

    date_added = models.DateTimeField(auto_now_add=True)
    images = models.ManyToManyField(Image, related_name="images_inc", blank=True, null=True)

    ....


    def __unicode__(self):
        return u'%s #%s' % (self.title, self.number)
    def get_absolute_url(self):
        return "/issues/%s" % self.slug     
    class Meta:
        ordering = ['-date_added']

Views.py

def index(request):
    ....

    all_characters = Character.objects.all().filter(is_featured=True).order_by('name')
    latest_issues = Issue.objects.order_by('-date_added')[:10]

    ....

    t = loader.get_template('comics/index.html')
    c = Context({
        'all_characters': all_characters,
        'latest_issues': latest_issues,
       })
    return HttpResponse(t.render(c))

Now, here is how my index.html file is setup:

{% for issue in latest_issues %} 
<li class="gallery">
<a href="{{ issue.get_absolute_url }}">
<img alt="{{ issue.title }} #{{ issue.number }}" title="{{ issue.title }} #{{ issue.number }}" src="{{ issue.images }}"></a>
<em>{{ issue.title }} #{{ issue.number }}</em>
</li>
{% endfor %}

{{ issue.images }} displays one of those ManyToManyDBManagex34982423 things and {{ issue.images.all }} displays something like "Image: Astonishing X-Men 1 Cover A" while {{ issue.images.url }} displays nothing.

I need it to display the cover image and more, specifically, I need it display ONE image that is categorized as 'Cover,' because sometimes there are variant covers, and I wouldn't want it to display two covers of one issue. I'm sure I'd have to fix my views.py, but how would I go about doing this and then how would I display it in my template?

Baby talk. I am new to this. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜清冷一曲。 2024-11-10 12:21:21

这不是切片,您将获得索引 10:

views.py:

latest_issues = Issue.objects.order_by('-date_added')[10]

您想要:

latest_issues = Issue.objects.order_by('-date_added')[:10]

显示某个问题的所有封面图像:

{% for image in issue.images.all %}
    {% if image.category == 'Cover' %}
    <img src='{{ image.image.url }}' />
    {% endif %}
{% endfor %}

That's not slicing, you are getting index 10:

views.py:

latest_issues = Issue.objects.order_by('-date_added')[10]

you would want:

latest_issues = Issue.objects.order_by('-date_added')[:10]

To display all the cover images for an issue:

{% for image in issue.images.all %}
    {% if image.category == 'Cover' %}
    <img src='{{ image.image.url }}' />
    {% endif %}
{% endfor %}
你在我安 2024-11-10 12:21:21

实现此目的的一种方法是在 Issue 类上创建一个属性来保存指定为“封面”的图像。这使您的模板尽可能简单。如果您只想显示一张封面,那么向您的模型管理(或在问题模型上进行编辑的任何地方)添加一个干净的方法也可能是有意义的,以仅允许将一张图像指定为“封面” ”。

#NOT TESTED
#models.py
from django.utils.functional import memoize

class Issue(models.Model):
    images = models.ManyToManyField(Image, blank=True, null=True)

    @memoize
    @property # @property means this is read-only
    def cover(self):
        return self.images.filter(category__exact='Cover')[:1]

#views.py
def index(request):
    latest_issues = Issue.objects.order_by('-date_added').select_related(depth=1)[:10]
    return render(request, 'comics/index.html',
        {'latest_issues' : latest_issues})

#latest_issues.html
{% for issue in latest_issues %} 
<li class="gallery">
    <a href="{{ issue.get_absolute_url }}">
        <img alt="{{ issue.title }} #{{ issue.number }}" title="{{ issue.title }}
            #{{ issue.number }}" src="{{ issue.cover.url }}">
    </a>
    <em>{{ issue.title }} #{{ issue.number }}</em>
</li>
{% endfor %}

您可能会考虑使用整数而不是字符串来保存类别的值,并将选项和选项元组放入一个单独的文件中,以便您可以更轻松地在多个位置访问它们。我倾向于将它们放入“constants.py”文件中,即使 Python 没有常量。

希望对您有所帮助。

One way to do this is to create a property on the Issue class to hold the Image specified as a "cover". This keeps your template as simple as possible. If you're only wanting to display one cover, it might also make sense to add a clean method to your model admin (or wherever you're doing editing on the Issue model) to only allow one image to be specified as a "cover".

#NOT TESTED
#models.py
from django.utils.functional import memoize

class Issue(models.Model):
    images = models.ManyToManyField(Image, blank=True, null=True)

    @memoize
    @property # @property means this is read-only
    def cover(self):
        return self.images.filter(category__exact='Cover')[:1]

#views.py
def index(request):
    latest_issues = Issue.objects.order_by('-date_added').select_related(depth=1)[:10]
    return render(request, 'comics/index.html',
        {'latest_issues' : latest_issues})

#latest_issues.html
{% for issue in latest_issues %} 
<li class="gallery">
    <a href="{{ issue.get_absolute_url }}">
        <img alt="{{ issue.title }} #{{ issue.number }}" title="{{ issue.title }}
            #{{ issue.number }}" src="{{ issue.cover.url }}">
    </a>
    <em>{{ issue.title }} #{{ issue.number }}</em>
</li>
{% endfor %}

You might consider using integers to hold the values for the categories instead of strings, and also putting the choices and choices tuple into a separate file so you can access them in more than one place a little easier. I tend to put these into a "constants.py" file, even though Python doesn't have constants.

Hope that helps you out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文