9

The normal way to start the Django server is to run the following command from a terminal or a bash script:

python manage.py runserver [Ip.addr]:[port] 

e.g.

python manage.py runserver 0.0.0.0:8000

How can I start a Django server from a Python script?

One option is the following

import os
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
    from django.core.management import execute_from_command_line
    args = ['name', 'runserver', '0.0.0.0:8000']
    execute_from_command_line(args)

Is there a better way?

2
  • 2
    Why do you want to start it from a python script? Commented Jun 17, 2015 at 13:43
  • 1
    I would suggest using an actual webserver, like the docs recommend. Commented Jun 17, 2015 at 14:01

2 Answers 2

16

Python has already builtin HTTP server

python -m SimpleHTTPServer

OR you have an alternative to run the django server

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")

from django.core.management import call_command
from django.core.wsgi import get_wsgi_application 
application = get_wsgi_application()
call_command('runserver',  '127.0.0.1:8000')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer but I'm getting this error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
before call_command , you can try : from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
yes that works, Edit your answer and I'll select it as the write answer
1

Just responding to this because I found a way to automize the django runserver command and open the project on the broswer:

import os
import webbrowser
import asyncio


# RUNSERVER
async def runserver():
    path = "D:\Your\Django\Project\Full\Path\SimpleBlog"
    os.chdir(path)
    os.system("py manage.py runserver")

# OPEN BROWSER
def openproject():
    webbrowser.open_new_tab("http://127.0.0.1:8000/index")

# EXECUTE PROGRAM
async def main():
    task1 = asyncio.create_task(runserver())
    openproject()
    await task1



asyncio.run(main())

Thats the script. Then I made the executable version of it with pyinstaller module and created a shortcut on my desktop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.