Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Django is running under the development server

Tags:

python

django

Is there a way to determine if Django is running on localhost and setting the DEBUG variable in settings.py accordingly.

So that if I run the server locally it will set DEBUG to True and otherwise set it to False.

Localhost: python manage.py runserver
Not localhost: python manage.py runserver 0.0.0.0:8000

like image 594
Tyilo Avatar asked Aug 19 '12 15:08

Tyilo


People also ask

How do I know if Django server is running?

To verify the Django project, make sure your virtual environment is activated, then start Django's development server using the command python manage.py runserver . The server runs on the default port 8000, and you see output like the following output in the terminal window: Performing system checks...

What server does Django use for development?

For Django this will usually be the Gunicorn web application server (with a . wsgi script). wsgi.py: WSGI configuration to call our Django application in the Railway environment.

How do I run a Django development server?

The built-in development server is part of what the manage.py file offers in any Django Project. To run the development server you'll want to navigate to the project directory that holds your Django project. This can be done right from Visual Studio code if you like by clicking Terminal-> New Terminal like so.

Is Django a web server or application server?

Django is an extremely popular and fully featured server-side web framework, written in Python. This module shows you why Django is one of the most popular web server frameworks, how to set up a development environment, and how to start using it to create your own web applications.


2 Answers

This is not the best approach, but it works :)
For something better you can use django-configurations

import sys    
# Determine if in Production or Development
if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'):
    DEBUG = True 
    #...       
else:
    DEBUG = False
    #...

Or you can use it as one-liner as mentioned by little_birdie in the comments:
DEBUG = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')

like image 53
Slipstream Avatar answered Sep 27 '22 03:09

Slipstream


As suggested by Bernhard Vallant, you can just check for runserver in sys.argv.

You can just replace your DEBUG assignment in settings.py with this:

DEBUG = (sys.argv[1] == 'runserver')

You should also import sys somewhere in settings.py.

like image 41
Tyilo Avatar answered Sep 26 '22 03:09

Tyilo