Django - ImportError: Could not import 'drf_yasg.generators.OpenAPISchemaGenerator' for API setting

20.9k views Asked by At

I'm trying to add https://github.com/axnsan12/drf-yasg this library to our django application and getting the below error.

permission_classes=(permissions.AllowAny,),
  File "/env/lib/python3.7/site-packages/drf_yasg/views.py", line 67, in get_schema_view
    _generator_class = generator_class or swagger_settings.DEFAULT_GENERATOR_CLASS
  File "env/lib/python3.7/site-packages/drf_yasg/app_settings.py", line 122, in __getattr__
    val = perform_import(val, attr)
  File "env/lib/python3.7/site-packages/rest_framework/settings.py", line 166, in perform_import
    return import_from_string(val, setting_name)
  File "env/lib/python3.7/site-packages/rest_framework/settings.py", line 180, in import_from_string
    raise ImportError(msg)
ImportError: Could not import 'drf_yasg.generators.OpenAPISchemaGenerator' for API setting 'DEFAULT_GENERATOR_CLASS'. ImportError: cannot import name 'URLPattern' from 'rest_framework.compat' (env/lib/python3.7/site-packages/rest_framework/compat.py).

after some research I found some people suggested installing this package to solve the issue

pip3 install packaging 

But this is not making any difference. Any other good api documentation library available for django rest api?

4

There are 4 answers

4
Eugene Prikazchikov On

Looks like DRF does not have rest_framework.compat.URLPattern starting from version 3.12, and drf-yasg have not caught up on this yet. Make sure that your DRF version is less than 3.12. For example: pip install djangorestframework==3.11.2

4
JPG On

UPDATE

The issue has been fixed in drf-yasg==1.20.0--(Release notes) so that you can upgrade to the latest version by

pip install drf-yasg -U

Original answer

There is an open issue in drf-yasg-(#641) to fix this issue. Unfortunately, the project is no longer maintained given that there has been no activity since Feb 2020 (Ref this).

But, @JoelLefkowitz created a fork of the project and it is available in named drf-yasg2 which has been fixed the OP's issue.

What you need to do is, migrate from drf-yasg to drf-yasg2--(ReadTheDoc)

Installation

pip install drf-yasg2

and add it to the INSTALLED_APPS section

INSTALLED_APPS = [
      ...
      'drf_yasg2',
      ...
   ]
0
Vishal Singh On

The following worked for me

pip install drf-yasg -U
0
Suman Lamichhane On

It could surely help you guys write this in settings.py file:

SWAGGER_SETTINGS = { "DEFAULT_GENERATOR_CLASS": "rest_framework.schemas.generators.BaseSchemaGenerator", }