I am trying to filter an image through a category. It works but not the way I want it to. Here are how my models are setup:
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):
...
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 issue(request, issue_slug):
issue = get_object_or_404(Issue, slug=issue_slug)
cover = Image.objects.filter(category='Cover')
scan = Image.objects.filter(category='Scan')
return render_to_response('comics/issue_detail.html', {'issue': issue, 'cover': cover, 'scan': scan}, context_instance=RequestContext(request))
I am trying to filter it by Cover or Scan, as you can see, but when I put this into my template:
{{ cover }} or {{ scan }}
It returns:
<Image: Astonishing X-Men 1 Cover A>] [<Image: Astonishing X-Men 1, teamshot>]
I need it to return the image URL, obviously. Adding {{ cover.url }} doesn’t work.
Oh, and I just realized it does not display the specific image that is in the issue. It displays ALL images that categorized as either Scan or Cover.
In your current code, you’re returning all the images, even the ones that aren’t associated with your chosen comic issue. I’m assuming you want the ones for the selected issue. You probably want to do this instead:
Then, in the template:
Update
If you do want more than one cover or scan, then you don’t want to get only the first item. And really, you should probably just move this logic to
models.pyto avoid possible code duplication.Something like this would be better:
Then, in the template: