9

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>
Josh Silveous
  • 479
  • 2
  • 6
  • 16
  • 4
    If you're using Django then why not generate the random number in the view and pass it to the template from there? – MrAlexBailey Apr 20 '16 at 12:44
  • 1
    Any Python code in your Django/Python project? ;-) – Alfe Apr 20 '16 at 12:44
  • i can help you to accomplish @Jkdc method (in comment).... ! – Mbambadev Apr 20 '16 at 12:46
  • If you are looking for a quick solution, then you can simply use Javascript: `Math.random()`, i.e. do it on the client; if you need to do it to figure out how to pass values from Django, then Alfe already made the right suggestion. If you go through the documentations you will find examples. – Cyb3rFly3r Apr 20 '16 at 13:03
  • A lot of people have lambasted the above post for asking the question - but it's a fair question. Best way to do anything like this is template_tags - to be used across a number of templates (I wouldn't use view.py to pass such variables as you'll be restricted to one context rendering). –  Nov 05 '17 at 14:46
  • Just in case if anybody interested in generating unique number here it is **{% now 'U' %}** this will return epoch/unixtimestamp. note this is not random this is easily guessable. – Kaushal May 19 '22 at 15:05

3 Answers3

23

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/

drdaeman
  • 11,159
  • 7
  • 59
  • 104
4

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 }}
art_hq
  • 81
  • 5
2

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

Andrey Kachow
  • 936
  • 7
  • 22