How to generate a random number in a Template Django python?

If for some reason you don't want to create a custom tag or pass the value from the view function, you can try this:

in your template:

{{ request.user.your_model.your_randint }}

in any model.py file of your application:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from random import randint

class Your_model(models.Model):
    user = models.OneToOneField(User,
                                on_delete=models.CASCADE,
                                primary_key=True)
    @staticmethod
    def your_randint():
        return str(randint(0, 2048))

    @receiver(post_save, sender=User)
    def create_latest_inputs(sender, instance, created, **kwargs):
        if created:
            Your_model.objects.create(user=instance)

The last method is required to automatically create Your_model every time a User model is created.

By the way, you don't have to create one-to-one field with user, you can add this static method to any model, which was sent to a page.

P.S. You may need to run migrations


There is no built-in way to do this. If all you need is a random value, once, and you don't want to pass that from a view function - I guess a custom template tag is the way.

In any appropriate application, create a file templatetags/random_numbers.py (and an empty templatetags/__init__.py if you don't have any other custom template tags) with the following contents:

import random
from django import template

register = template.Library()

@register.simple_tag
def random_int(a, b=None):
    if b is None:
        a, b = 0, a
    return random.randint(a, b)

Then, in your template use it like this:

{% load random_numbers %}

<p>A random value, 1 ≤ {% random_int 1 10 %} ≤ 10.</p>

More documentation on custom tags: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/


For now (Django 3) you can do something like this, doc

view.py

list_for_random = range(100)
return render(...{'list_for_random': list_for_random,}) 

Then, in template just

{{ list_for_random | random }}