Python documentation for django.views.generic with pydoc

大城市里の小女人 提交于 2019-12-06 02:25:51

问题


When I run the command:

pydoc django.views.generic

I get the error:

problem in django.views.generic - 
<class 'django.core.exceptions.ImproperlyConfigured'>:
Requested setting DEFAULT_INDEX_TABLESPACE, 
but settings are not configured. You must either define 
the environment variable DJANGO_SETTINGS_MODULE or call 
settings.configure() before accessing settings

How can I get the pydoc documentation for django.views.generic?


回答1:


Importing many of Django's modules pulls in other modules that depend on being in a Django project environment. Create a dummy project, and use its settings.

$ django-admin.py startproject dummy
$ cd ./dummy
$ DJANGO_SETTINGS_MODULE=dummy.settings pydoc django.views.generic

Note the last line that sets the env var DJANGO_SETTINGS_MODULE to the import path of the settings.py file. Normally, you don't need this since manage.py and wsgi.py set this up for you, but pydoc knows nothing about this.

If you already have a project, you can obviously skip the dummy project and just use your project's settings.


When using newer versions of Django, you also need to call django.setup() before Django is generally usable. Wrap pydoc in a script to do this, rather than calling pydoc directly.

my_pydoc.py

import django
import pydoc
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'dummy.settings'
django.setup()
pydoc.cli()
python my_pydoc.py django.views.generic



回答2:


While davidism's answer works for some things, it won't work for my own apps, as I got an AppRegistryNotReady exception. I found I needed to do some ad-hockery in my app files to get it to work:

import sys
importer = sys.modules['__main__'].__spec__
if importer.name == 'pydoc':
    import django
    django.setup()

Source

Finally it works, at least for views.py. Other files may need other solutions. This feels brittle and version-dependent, but it is working for Django 1.10.2 and Python 3.5.2.


sys.argv[0] has the same info, /usr/lib/python3.5/pydoc.py, so it could be accomplished more simply and reliably by:

import sys, os
if os.path.splitext(os.path.basename(sys.argv[0]))[0] == 'pydoc':
    import django
    django.setup()


来源:https://stackoverflow.com/questions/24772805/python-documentation-for-django-views-generic-with-pydoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!