Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python random.random() causes "'module' object is not callable" when used in custom template tag [duplicate]

If I start python from the command line and type:

import random
print "Random: " + str(random.random())

It prints me a random number (Expected, excellent).

If I include the above-two lines in my django application's models.py and start my django app with runserver I get the output on the command line showing me a random number (Great!)

If I take a custom tag which works perfectly fine otherwise, but I include

import random
print "Random: " + str(random.random())

as the first 2 lines of the custom tag's .py file, I get an error whenever I try to open up a template which uses that custom tag:

TypeError at /help/
'module' object is not callable

Please keep in mind that if I get rid of these two lines, my custom tag behaves as otherwise expected and no error is thrown. Unfortunately, I need some random behavior inside of my template tag.

The problem is if in a custom tag I do:

import random

on a custom template tag, it imports

<module 'django.templatetags.random' from '[snip path]'> 

and not

<module 'random' from 'C:\\Program Files\\Python26\\lib\\random.pyc'>

as is normally imported from everywhere else

Django template library has a filter called random, and somehow it is getting priority above the system's random.

Can anyone recommend how to explicitly import the proper python random?

like image 962
Krystian Cybulski Avatar asked May 08 '09 01:05

Krystian Cybulski


3 Answers

The answer is ... strange.

When I originally wrote my custom tag, I called it random.py. I quickly realized that this name may not be good and renamed it randomchoice.py and deleted my random.py file. Python kept the compiled random.pyc file around, and it was getting loaded whenever I did import random. I removed my random.pyc file, and the problem went away.

like image 163
Krystian Cybulski Avatar answered Oct 30 '22 06:10

Krystian Cybulski


Yes, this kind of error is pretty easy. Basically don't name any of your filenames or anything you create with the same names as any likely python modules you are going to use.

like image 21
Chris Avatar answered Oct 30 '22 06:10

Chris


Its been a while since I tinkered around with Django, but if random.random is a "module", then try random.random.random(). Or maybe just try random(). You just don't know what kind of hackery goes on behind the scenes.

Edit

Try this:

sys.path = [r"C:\Program Files\Python26\lib\"] + sys.path
import random
sys.path.pop(0)
like image 2
Unknown Avatar answered Oct 30 '22 08:10

Unknown