I'm trying to extend the flatpage django app to include some bootstrap carousel functionality. At this point i created a new django app called "carousel" and inside model.py i define a model class called "CarouselImage" that have an ImageField to upload the carousel images and a ForeignKey for the FlatPage.
model.py
from django.contrib.flatpages.models import FlatPage
class CarouselImage(models.Model):
image = models.ImageField(upload_to='carousel/')
page = models.ForeignKey(FlatPage)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
active = models.BooleanField(default=True)
def __str__(self):
return str(self.image)
At the carousel/admin.py i'm not having any problem, as you will see in this image 1.
admin.py
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from .models import CarouselImage
class CarouselInline(admin.TabularInline):
model = CarouselImage
extra = 1
allow_add = True
class FlatPageAdminWithCarousel(FlatPageAdmin):
inlines = [CarouselInline]
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdminWithCarousel)
Problem
After all, what i need to know is how i can pass this images to the template?. The problem is that FlatPage has already a view, so i can't create a view to pass those images to the template. I don't know if there is a way to extend a view to include another context.
One Stackoverflow QA pointed to the creation of templatetags, so i tried to create some template tags but if i can't pass those images as a context to the template the templatetags wont work.
templatetags/add_carousel.py
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def carousel(context):
image = context['image']
return str(image)
Thanks for all the help you can give,
Iván
You've missed the point of the template tags advice. The point is not to pass images from the context into the tag, but the other way round: query the images in the tag and then pass them into the context from there.
The best way to do this is to use an inclusion tag rather than a simple tag: an inclusion tag is associated with its own template fragment which it renders with its own context, so you can include all elements related to your carousel there, and from the full flatpage template you only need to call the tag itself.
Although actually now I look at your question again, I realise that you don't even need to do this. You have a foreign key from flatpage to image: you can get the images for a page with page.carouselimage_set.all
. That makes the template tag irrelevant.