Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template Tags - Return multiple values or object

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 %}
like image 696
xXPhenom22Xx Avatar asked Mar 28 '13 13:03

xXPhenom22Xx


People also ask

How return multiple values Django?

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.

What is the use of template tag in Django?

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.

Do Django templates have multiple extends?

Yes you can extend different or same templates.

What does {% %} mean in Django?

{% %} 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.


1 Answers

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 }}
like image 132
Daniel Roseman Avatar answered Sep 28 '22 18:09

Daniel Roseman