Malthe Have Musaeus
Malthe Have Musaeus

Reputation: 404

Django2. Python vaiable in seperate file

Hello I'm doing a Python Django project and everything is going great so far!

I have a separate python file called number.py, and in that file I have a variable named "testvar". I can pass that to my index.html with views.py, but the random number in number.py is always the same when I reload the site and I need it to update everytime.

number.py

from random import *
testvar = randint(1, 100)

views.py

from django.shortcuts import render
from .number import testvar

testvar = testvar
def index(request):
    return render(request, 'porsche/index.html', {'testvar' : testvar})

And please tell me if there is a smarter way of doing this, thanks!

Upvotes: 0

Views: 37

Answers (2)

JPG
JPG

Reputation: 88619

you can use it directly in view as,

from django.shortcuts import render
from random import randint


def index(request):
    return render(request, 'porsche/index.html', {'testvar': randint(1, 100)})

Upvotes: 0

Adelina
Adelina

Reputation: 11931

in number.py

def get_random_number():
    return randint(1, 100)

in views.py

def index(request):
    return render(request, 'porsche/index.html', {'testvar' : get_random_number()})

Upvotes: 1

Related Questions