Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Okay, so I'm trying to make a random number generator webpage using Django/Python. What I need to accomplish to do that is somehow use python code in my HTML template file, except I can't find out how to do that.

<h1 style="font-size:50px;line-height:20px;color:rgb(145,0,0);font-    family: Arial Black, Gadget, sans-serif"></h1>
<h2 style="line-height:10px;color:rgb(140,140,140)"></h2>
<h3 style="font-size:40px;line-height:10px;font-family: Arial Black, Gadget, sans-serif"></h3>
<body style="background-color:rgb(255,239,154)"></body>
<!--Style placeholders-->


<h1 style="text-align:center;position:relative;top:20px">
Test Site
</h1>

<!--Reroll icon-->
<h1 style="text-align:center;position:relative;top:20px">
<input type='image' style='width:60px;height:56px;' src='../../static/polls/dice.png' alt='Re-roll'
onclick='location.reload();' value='Roll' /></h1>
like image 670
Josh Silveous Avatar asked Apr 20 '16 12:04

Josh Silveous


People also ask

Can you do math in Django template?

Use django-mathfilters. In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value. For the specific example above, you would use {{ 100|sub:object.

How do you randomly generate numbers in Python?

To generate random number in Python, randint() function is used. This function is defined in random module.

How do you generate a random number from 1 to 9 in Python?

Use a random.randint() function to get a random integer number from the inclusive range. For example, random.randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].


3 Answers

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/

like image 151
drdaeman Avatar answered Oct 13 '22 17:10

drdaeman


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 }}
like image 23
art_hq Avatar answered Oct 13 '22 17:10

art_hq


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

like image 31
Andrey Kachow Avatar answered Oct 13 '22 16:10

Andrey Kachow