views:

1670

answers:

3

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?

+1  A: 

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)
Unknown
Thanks for the insight. I tried all that, and next I tried to print out which exact module it is importing. This added in important insight into the problem, which I included in the main post.
+7  A: 

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". 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 goes away.

I thank you all for your help.

A: 

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.

Chris