I have a Django (1.5) template tag that I am using in a partial view to render some random content. The tag makes a query for a single record. I have no problem returning a single item but when trying to send back the full object for use or multiple items I am having trouble.
Here is my tag
@register.inclusion_tag('_footer.html')
def get_random_testimonial():
# Grab random record
record = Testimonials.objects.order_by('?')[0]
return record.text
I would like to be able to return both record.text and record.id to the template tag
To render the tag I have this in my _footer.html view
{% load current_tags %}
{% get_random_testimonial %}
Is there a way I can just return the record object and be able to get all of the values of that object with something like:
{% get_random_testimonial.text %}
{% get_random_testimonial.id %}
In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.
Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.
Yes you can extend different or same templates.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
This doesn't make sense as an inclusion tag. Especially as you seem to be using it in the same template as you have told it to render.
What you need is an assignment tag:
@register.assignment_tag
def get_random_testimonial():
return Testimonials.objects.order_by('?')[0]
Then you can do:
{% get_random_testimonial as my_testimonial %}
{{ my_testimonial.text }}
{{ my_testimonial.id }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With