Error exception in wsgi application

Django ImproperlyConfigured: WSGI application ‘myproject.wsgi.application’ could not be loaded; Error importing module

I have an almost fresh install of django and when I run python runserver . It is giving me this error:

ImproperlyConfigured: WSGI application ‘myproject.wsgi.application’ could not be loaded; Error importing module.

10 Answers 10

Comment out the

in your file in Middleware

From my experience this happens when I try to execute runserver but I haven’t installed all custom MIDDLEWARE in After identifying and installing the middlewares the error is resolved.

Check the,

remove ‘whitenoise.middleware.WhiteNoiseMiddleware’, or install Whitenoise (pip install whitenoise)

Check for the stack trace — you might find answer few lines above the line «The above exception was the direct cause of the following exception:»

It may caused for example by using of middleware from some uninstalled third party app etc.

One of the reason for this issue is if you have a middleware added into django middleware list in but haven’t installed it yet.

In my case I added corsheaders.middleware.CorsMiddleware which wasn’t installed.I installed it using pip install django-cors-headers and that did the trick.

I encountered the same problem because I added the debug_toolbar Middleware to my

I solved the problem by removing the debug_toolbar Middleware. I also had to remove debug_toolbar from my INSTALLED APPS.


django.core.exceptions.ImproperlyConfigured: WSGI application ‘wsgi.application’ could not be loaded; Error importing module

I used to check every answer to this question but NOTHING helped me. Here’s a full Traceback :

Please see my full project on github:

2 Answers 2

Please make sure to add your app in the project’s file under INSTALLED_APPS.
I was facing the same error, when i had mistakenly added the app under the MIDDLEWARE section.

After a long struggle to get things to work I was able to successfully run the server after making changes from WSGI to asgi configuration, Its not a bad thing as asgi is a successor to WSGI open delete the WSGI configuration or comment to hide it like the way I did

then create the file named and paste this code inside it

DjangoBlog is the name of my project change it to suit yours


Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.12.43152

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.


django.core.exceptions.ImproperlyConfigured: WSGI application ‘application’ could not be loaded

The scenario is,

I cloned the Django code for OpenShift-V3 from here . When I ran the code with python runserver , I got this error:

django.core.exceptions.ImproperlyConfigured: WSGI application ‘application’ could not be loaded; Error importing module: ‘application doesn’t look like a module path

I didn’t add anything to the code and the required packages are already satisfied.

27 Answers 27

I used a middleware CorsMiddleware but forget to install it so after install, it works perfectly.

pip install django-cors-headers

So check something like it you may miss something like it.

Read carefully, it might say «The above exception was the direct cause of the following exception: . «. And the «above exception» being you forgot to install whitehoise. Run pip install whitenoise , it worked for me.

Go to django-ex/project/

Change the line in as below

WSGI_APPLICATION = ‘application’ to WSGI_APPLICATION = ‘wsgi.application’

If you run django project locally for development, just remove WSGI_APPLICATION variable from module. It needs in prod/stage settings, for example

Do you have Django Debug Toolbar

Remove it and check if the problem goes away. Possible occurences:

This worked for me

Install this if you didn’t before:

in add :

Although solved my problem. Generally produced while we are moving a project to different virtual enviroments. Sometimes we forgot to install the package & whitenoise just broke the application little bit, because no where it is mentioned that you are missing «whitenoise» module.

in file change as follows:

note that any error in importing modules anywhere prior to starting the wsgi application will also prompt this message, so first look at the trace and start from the top in fixing issues.

I ported a Django app from python 2.7 to python3 and add all sorts of module import issues, not connected to this issue directly.

I was using django-cors-headers, then I thought I haven’t implemented cors in my project, so went ahead to install django-cors-middleware, then it’s started giving the wsgi exception, so i checked the stack trace and I found out that it’s django-cors-headers and django-cors-middleware conflicting each other. I had to uninstall django-cors-middleware but it’s still gives the same exception, so uninstall django-cors-headers too then reinstall and everything works fine.

Same problem.. I checked whether django-cors-middleware and django-cors-headers installed or not. I found those were not installed and then I installed them.

  1. python -m pip install django-cors-middleware
  2. python -m pip install django-cors-headers
  1. python migrate
  2. python runserver

Finally, it’s worked.

Check your middleware and delete error string

Go to :

  • In MIDDLEWARE, check whether you have added anything which is not working.
  • In INSTALLED_APPS, check whether you have added the apps or not. If not, add all the apps you have created for this project.
Читайте также:  Javascript try error message

Example: I had this error today and was totally unaware why is this happening then after checking for a while, I have found a very silly mistake e.g. I have added my newly created app in the MIDDLEWARE instead of INSTALLED_APPS.

In the latest version of Django, to add your app in installed apps in file, write —

I tried all these solution and the one worked for me was this:

This module was missing and not mentioned in requirements.txt Shows long error message that ends with wsgi application improperly configured. But somewhere in middle I could see «No module named ‘htmlmin’ I installed and it is resolved.

maybe using middleware is the simple way to fix this , this problem mostly happens about cors Policy


It happens when you insert something in MIDDLEWARE = [. ] solution tire to put added latest addend things at top of middleware.

You may also get this error while adding your custom middleware. While adding it, make sure you so it like this: folder_contains_your_middleware_file.middleware_file.middleware_class

Below is my example:

I also had the same problem, in spite of trying all the above solutions I was facing the same issue. I noticed that before this error I was getting the below error:

To resolve this error I installed the django-log-request-id package using pip install django-log-request-id and both the issues got resolved.

I removed the custom middleware, but forgot to exclude it from MIDDLEWARES in the module, so be sure to verify that as well.

Inspecting the logs, the same error was thrown due to a «WhitenoiseMiddleware» error, such as this.


Hello, I tried to run the code, but it shows #71


qwelin commented Dec 22, 2016

Hello, I tried to run the code, but it shows:
django.core.exceptions.ImproperlyConfigured: WSGI application ‘application’ could not be loaded; Error importing module: ‘application doesn’t look like a module path’

The text was updated successfully, but these errors were encountered:

PI-Victor commented Dec 22, 2016

can you be a bit more specific? where does this error appear, on openshift, on your local system, did you follow all of the steps provided in the, are you running the example or your own example?
I’m familiar with this error, but i don’t exactly remember where i saw it before, or how i bumped into it. It’s not an error in the example, though.

qwelin commented Dec 23, 2016

on mine local system,liunx.yes , I was follow all of the steps provided in the and I running the example.

(text_1) MacxdeMacBook-Pro-251:django-ex will$ ./ runserver
Performing system checks.

System check identified no issues (0 silenced).
December 22, 2016 — 10:15:46
Django version 1.8, using settings ‘project.settings’
Starting development server at
Quit the server with CONTROL-C.
Unhandled exception in thread started by
Traceback (most recent call last):
File «/Users/Macx/text_1/lib/python3.5/site-packages/django/utils/», line 21, in import_string
module_path, class_name = dotted_path.rsplit(‘.’, 1)
ValueError: not enough values to unpack (expected 2, got 1)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «/Users/Macx/text_1/lib/python3.5/site-packages/django/core/servers/», line 50, in get_internal_wsgi_application
return import_string(app_path)
File «/Users/Macx/text_1/lib/python3.5/site-packages/django/utils/», line 24, in import_string
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
File «/Users/Macx/text_1/lib/python3.5/site-packages/django/utils/», line 658, in reraise
raise value.with_traceback(tb)
File «/Users/Macx/text_1/lib/python3.5/site-packages/django/utils/», line 21, in import_string
module_path, class_name = dotted_path.rsplit(‘.’, 1)
ImportError: application doesn’t look like a module path

During handling of the above exception, another exception occurred:


HTTP Exceptions¶

Implements a number of Python exceptions which can be raised from within a view to trigger a standard HTTP non-200 response.

Usage Example¶

As you can see from this example those exceptions are callable WSGI applications. However, they are not Werkzeug response objects. You can get a response object by calling get_response() on a HTTP exception.

Keep in mind that you may have to pass an environ (WSGI) or scope (ASGI) to get_response() because some errors fetch additional information relating to the request.

If you want to hook in a different exception page to say, a 404 status code, you can add a second except for a specific subclass of an error:

Error Classes¶

The following error classes exist in Werkzeug:

exception werkzeug.exceptions. BadRequest ( description = None , response = None ) ¶

400 Bad Request

Raise if the browser sends something to the application the application or server cannot handle.

exception werkzeug.exceptions. Unauthorized ( description = None , response = None , www_authenticate = None ) ¶

Raise if the user is not authorized to access a resource.

The www_authenticate argument should be used to set the WWW-Authenticate header. This is used for HTTP basic auth and other schemes. Use WWWAuthenticate to create correctly formatted values. Strictly speaking a 401 response is invalid if it doesn’t provide at least one value for this header, although real clients typically don’t care.

description (str | None) – Override the default message used for the body of the response.

www-authenticate – A single value, or list of values, for the WWW-Authenticate header(s).

Changed in version 2.0: Serialize multiple www_authenticate items into multiple WWW-Authenticate headers, rather than joining them into a single value, for better interoperability.

Changed in version 0.15.3: If the www_authenticate argument is not set, the WWW-Authenticate header is not set.

Changed in version 0.15.3: The response argument was restored.

Changed in version 0.15.1: description was moved back as the first argument, restoring its previous position.

Читайте также:  Error a2005 symbol redefinition

Changed in version 0.15.0: www_authenticate was added as the first argument, ahead of description .

Raise if the user doesn’t have the permission for the requested resource but was authenticated.

exception werkzeug.exceptions. NotFound ( description = None , response = None ) ¶

Raise if a resource does not exist and never existed.

exception werkzeug.exceptions. MethodNotAllowed ( valid_methods = None , description = None , response = None ) ¶

405 Method Not Allowed

Raise if the server used a method the resource does not handle. For example POST if the resource is view only. Especially useful for REST.

The first argument for this exception should be a list of allowed methods. Strictly speaking the response would be invalid if you don’t provide valid methods in the header which you can do with that list.

Takes an optional list of valid http methods starting with werkzeug 0.3 the list will be mandatory.

exception werkzeug.exceptions. NotAcceptable ( description = None , response = None ) ¶

406 Not Acceptable

Raise if the server can’t return any content conforming to the Accept headers of the client.

exception werkzeug.exceptions. RequestTimeout ( description = None , response = None ) ¶

408 Request Timeout

Raise to signalize a timeout.

exception werkzeug.exceptions. Conflict ( description = None , response = None ) ¶

Raise to signal that a request cannot be completed because it conflicts with the current state on the server.

New in version 0.7.

exception werkzeug.exceptions. Gone ( description = None , response = None ) ¶

Raise if a resource existed previously and went away without new location.

exception werkzeug.exceptions. LengthRequired ( description = None , response = None ) ¶

411 Length Required

Raise if the browser submitted data but no Content-Length header which is required for the kind of processing the server does.

exception werkzeug.exceptions. PreconditionFailed ( description = None , response = None ) ¶

412 Precondition Failed

Status code used in combination with If-Match , If-None-Match , or If-Unmodified-Since .

exception werkzeug.exceptions. RequestEntityTooLarge ( description = None , response = None ) ¶

413 Request Entity Too Large

The status code one should return if the data submitted exceeded a given limit.

exception werkzeug.exceptions. RequestURITooLarge ( description = None , response = None ) ¶

414 Request URI Too Large

Like 413 but for too long URLs.

exception werkzeug.exceptions. UnsupportedMediaType ( description = None , response = None ) ¶

415 Unsupported Media Type

The status code returned if the server is unable to handle the media type the client transmitted.

exception werkzeug.exceptions. RequestedRangeNotSatisfiable ( length = None , units = ‘bytes’ , description = None , response = None ) ¶

416 Requested Range Not Satisfiable

The client asked for an invalid part of the file.

New in version 0.7.

Takes an optional Content-Range header value based on length parameter.

exception werkzeug.exceptions. ExpectationFailed ( description = None , response = None ) ¶

417 Expectation Failed

The server cannot meet the requirements of the Expect request-header.

New in version 0.7.

exception werkzeug.exceptions. ImATeapot ( description = None , response = None ) ¶

418 I’m a teapot

The server should return this if it is a teapot and someone attempted to brew coffee with it.

New in version 0.7.

exception werkzeug.exceptions. UnprocessableEntity ( description = None , response = None ) ¶

422 Unprocessable Entity

Used if the request is well formed, but the instructions are otherwise incorrect.

exception werkzeug.exceptions. Locked ( description = None , response = None ) ¶

Used if the resource that is being accessed is locked.

exception werkzeug.exceptions. FailedDependency ( description = None , response = None ) ¶

424 Failed Dependency

Used if the method could not be performed on the resource because the requested action depended on another action and that action failed.

exception werkzeug.exceptions. PreconditionRequired ( description = None , response = None ) ¶

428 Precondition Required

The server requires this request to be conditional, typically to prevent the lost update problem, which is a race condition between two or more clients attempting to update a resource through PUT or DELETE. By requiring each client to include a conditional header (“If-Match” or “If-Unmodified- Since”) with the proper value retained from a recent GET request, the server ensures that each client has at least seen the previous revision of the resource.

exception werkzeug.exceptions. TooManyRequests ( description = None , response = None , retry_after = None ) ¶

429 Too Many Requests

The server is limiting the rate at which this user receives responses, and this request exceeds that rate. (The server may use any convenient method to identify users and their request rates). The server may include a “Retry-After” header to indicate how long the user should wait before retrying.

retry_after (datetime | int | None) – If given, set the Retry-After header to this value. May be an int number of seconds or a datetime .

Changed in version 1.0: Added retry_after parameter.

431 Request Header Fields Too Large

The server refuses to process the request because the header fields are too large. One or more individual fields may be too large, or the set of all headers is too large.

exception werkzeug.exceptions. UnavailableForLegalReasons ( description = None , response = None ) ¶

451 Unavailable For Legal Reasons

This status code indicates that the server is denying access to the resource as a consequence of a legal demand.

exception werkzeug.exceptions. InternalServerError ( description = None , response = None , original_exception = None ) ¶

500 Internal Server Error

Raise if an internal server error occurred. This is a good fallback if an unknown error occurred in the dispatcher.

Changed in version 1.0.0: Added the original_exception attribute.

The original exception that caused this 500 error. Can be used by frameworks to provide context when handling unexpected errors.

exception werkzeug.exceptions. NotImplemented ( description = None , response = None ) ¶

Читайте также:  Spring boot server error

501 Not Implemented

Raise if the application does not support the action requested by the browser.

exception werkzeug.exceptions. BadGateway ( description = None , response = None ) ¶

502 Bad Gateway

If you do proxying in your application you should return this status code if you received an invalid response from the upstream server it accessed in attempting to fulfill the request.

exception werkzeug.exceptions. ServiceUnavailable ( description = None , response = None , retry_after = None ) ¶

503 Service Unavailable

Status code you should return if a service is temporarily unavailable.

retry_after (datetime | int | None) – If given, set the Retry-After header to this value. May be an int number of seconds or a datetime .

Changed in version 1.0: Added retry_after parameter.

504 Gateway Timeout

Status code you should return if a connection to an upstream server times out.

exception werkzeug.exceptions. HTTPVersionNotSupported ( description = None , response = None ) ¶

505 HTTP Version Not Supported

The server does not support the HTTP protocol version used in the request.

exception werkzeug.exceptions. ClientDisconnected ( description = None , response = None ) ¶

Internal exception that is raised if Werkzeug detects a disconnected client. Since the client is already gone at that point attempting to send the error message to the client might not work and might ultimately result in another exception in the server. Mainly this is here so that it is silenced by default as far as Werkzeug is concerned.

Since disconnections cannot be reliably detected and are unspecified by WSGI to a large extent this might or might not be raised if a client is gone.

New in version 0.8.

exception werkzeug.exceptions. SecurityError ( description = None , response = None ) ¶

Raised if something triggers a security error. This is otherwise exactly like a bad request error.

New in version 0.9.


All the exceptions implement this common interface:

exception werkzeug.exceptions. HTTPException ( description = None , response = None ) ¶

The base class for all HTTP exceptions. This exception can be called as a WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages.

Changed in version 2.1: Removed the wrap class method.

__call__ ( environ , start_response ) ¶

Call the exception as WSGI application.

environ (WSGIEnvironment) – the WSGI environment.

start_response (StartResponse) – the response callable provided by the WSGI server.

get_response ( environ = None , scope = None ) ¶

Get a response object. If one was passed to the exception it’s returned directly.

environ (WSGIEnvironment | WSGIRequest | None) – the optional environ for the request. This can be used to modify the response depending on how the request looked like.

a Response object or a subclass thereof.

Special HTTP Exceptions¶

Starting with Werkzeug 0.3 some of the builtin classes raise exceptions that look like regular python exceptions (eg KeyError ) but are BadRequest HTTP exceptions at the same time. This decision was made to simplify a common pattern where you want to abort if the client tampered with the submitted form data in a way that the application can’t recover properly and should abort with 400 BAD REQUEST .

Assuming the application catches all HTTP exceptions and reacts to them properly a view function could do the following safely and doesn’t have to check if the keys exist:

If title or body are missing in the form, a special key error will be raised which behaves like a KeyError but also a BadRequest exception.

exception werkzeug.exceptions. BadRequestKeyError ( arg = None , * args , ** kwargs ) ¶

An exception that is used to signal both a KeyError and a BadRequest . Used by many of the datastructures.

Simple Aborting¶

Sometimes it’s convenient to just raise an exception by the error code, without importing the exception and looking up the name etc. For this purpose there is the abort() function.

werkzeug.exceptions. abort ( status , * args , ** kwargs ) ¶

Raises an HTTPException for the given status code or WSGI application.

If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:

If you want to use this functionality with custom exceptions you can create an instance of the aborter class:

class werkzeug.exceptions. Aborter ( mapping = None , extra = None ) ¶

When passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it’s a WSGI application it will be raised in a proxy exception.

The rest of the arguments are forwarded to the exception constructor.

Custom Errors¶

As you can see from the list above not all status codes are available as errors. Especially redirects and other non 200 status codes that do not represent errors are missing. For redirects you can use the redirect() function from the utilities.

If you want to add an error yourself you can subclass HTTPException :

This is the minimal code you need for your own exception. If you want to add more logic to the errors you can override the get_description() , get_body() , get_headers() and get_response() methods. In any case you should have a look at the sourcecode of the exceptions module.

You can override the default description in the constructor with the description parameter:


Оцените статью