Search code examples
djangotemplatesrandom-access

Random string in Django template


Is there any way to have a random string in a Django template?

I would like to have multiple strings displaying randomly like:

{% here generate random number rnd ?%}

{% if rnd == 1 %}
  {% trans "hello my name is john" %}
{% endif %}

{% if rnd == 2 %}
  {% trans "hello my name is bill" %}
{% endif %}

EDIT:
Thanks for answer but my case needed something more specific as it was in the base template (which I forgot to mention sorry ). So after crawling Google and some docs I fall on context processor article which did the job, I found it a little bit "heavy" anyway just for generating a random number...

here is the blog page : http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

Template tag did not the trick (or I did not find how) as it return a tag that cannot be translated as I remember (see blocktrans doc)

I did not find a way to generate a number for the base view (is there any?) and if there is a way better than context process I'd be glad to have some info.


Solution

  • I guess you want to have a tag that generates random strings from some table containing strings. See this Django snippet:

    http://djangosnippets.org/snippets/286/:

    # model
    class Quote(models.Model):
      quote = models.TextField(help_text="Enter the quote")
      by = models.CharField(maxlength=30, help_text="Enter the quote author")
      slug = models.SlugField(prepopulate_from=("by", "quote"), maxlength=25)
      def __str__(self):
        return (self.quote)
    
    # template tag
    from django import template
    register = template.Library()
    from website.quotes.models import Quote
    
    @register.simple_tag
    def random_quote():
      """
      Returns a random quote
      """
      quote = Quote.objects.order_by('?')[0]
    
      return str(quote)