Koliber Services Koliber Services - 1 month ago 4
Python Question

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

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?


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.