Python documentation for django.views.generic with pydoc

喜你入骨 提交于 2019-12-04 07:21:21

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
jcomeau_ictx

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