Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python documentation for django.views.generic with pydoc

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?

like image 337
Khamidulla Avatar asked Jul 16 '14 05:07

Khamidulla


2 Answers

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
like image 134
davidism Avatar answered Sep 23 '22 17:09

davidism


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()
like image 23
jcomeau_ictx Avatar answered Sep 23 '22 17:09

jcomeau_ictx