Python: can not import util
While reading the code for django/forms/widgets.py, I saw:
from util import flatatt
To dig deeper, I tried to import the util
module in a Python shell in my terminal, but I got an error:
Traceback (most recent call last):
File "<stdin>", line 1, in &开发者_开发技巧lt;module>
ImportError: No module named util
This left me confused. What is wrong?
Django is (ab?)using Python's import system in order to import something from django.forms.util
. Import that module instead.
In python, you get this ImportError:
Traceback (most recent call last):
File "b.py", line 3, in <module>
from util import flatatt
ImportError: No module named util
Some programmer out there created a library for your python script to use. Your program was unable to find that library. So the interpreter tells you that it can't be found. You have a few options. Either you have to define the library and functionality yourself, or you'll have to review the instructions and source code of the program you are trying to run, and try to figure out what is broken to prevent the library from being included. Or the final option is to remove any usage of that library in the current script.
You can define the module yourself like this:
Put this in util.py in the same directory as your widgets.py file.
def flatatt(prompt):
print("ok")
If you define that, you will get a different error, the script will import your library, and find that method, but then will do the wrong thing, because the programmer who designed that code probably had some other functionality in mind.
You need to figure out what you did wrong, or what the original programmer did wrong, or how your specific system is different to cause this to work.
You can learn more about what I've described above here, by rolling your own python modules: Python: How to import other Python files
Often times these sorts of bugs are barriers to entry, the original developers don't want programmers who don't know the difference between an integer
and a module
using the software. So little problems like this are added, to help encourage you that you need to develop a better understanding of the source code under the hood. It's like a mechanic helping everyone become better mechanics by swapping the wires on the distributor cap. It isn't going to work until you swap them back rightly.
from django.forms.utils import flatatt
It worked with django 1.11 version, and may work with 1.8 through 1.10
精彩评论