8

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
kollo
  • 1,285
  • 3
  • 20
  • 33

6 Answers6

25

Instead of using if-else blocks, passing a list of strings to your template and using random filter seems better

In your view:

my_strings = ['string1', 'string2', ...]
...
return render_to_response('some.html', {'my_strings':my_strings})

And in your template:

{{ my_strings|random }}

Here is the doc.

Mp0int
  • 18,172
  • 15
  • 83
  • 114
14

You could do something like that:

{# set either "1" or "2" to rnd, "12"|make_list outputs the list [u"1", u"2"] #}
{# and random chooses one item randomly out of this list #}

{% with rnd="12"|make_list|random %}
    {% if rnd == "1" %}
        {% trans "hello my name is john" %}
    {% elif rnd == "2" %}
        {% trans "hello my name is bill" %}
    {% endif %}
{% endwith %}

Look at the "Built-in template tags and filters" documentation for more info: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/

DanEEStar
  • 6,140
  • 6
  • 37
  • 52
  • 2
    I suppose this is only limited by the number of letters in unicode, but that `with` statement is going to get really weird really quickly. It's worth it though just so we can have the statement `{% elif rnd == "" %}` – mlissner Dec 10 '14 at 18:10
  • Looking at this makes me miss Jinja so much : ( Thank you, sir – Dany Mar 10 '19 at 16:55
4

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)
David Segonds
  • 83,345
  • 10
  • 45
  • 66
Priyank Patel
  • 3,495
  • 20
  • 20
0

You should write a custom template tag, see this one (with close functionality) as an example: http://djangosnippets.org/snippets/150/, but if it is not critical, to array of lines in the template, I would rather generete this random string in view.

dbf
  • 6,399
  • 2
  • 38
  • 65
0

In case you want to include random template and have it available globally :

in context_processors:

def sample(request):
  my_strings = ['string1', 'string2', ...]
  return {banners: my_stirngs}

in tempale (giving that your includes are in 'inc' folder ):

  {% with banners|random as template %}
    {% include 'inc/'|add:template %}
  {% endwith %}  
zzart
  • 11,207
  • 5
  • 52
  • 47
0

In a template:

{% random_number as rnd %}
The best 6 digits (by default) random number is: {{ rnd }}

{% random_number 9 as rnd9 %}
The best 9 digit random number is: {{ rnd9 }}

In markup.py:

@register.assignment_tag()
def random_number(length=6):
    from random import randint
    return randint(10**(length-1), (10**(length)-1))

Taken from https://djangosnippets.org/snippets/2984/

oriadam
  • 7,747
  • 2
  • 50
  • 48