Search code examples
djangodjango-runserver

Django: Avoid clash of port 8000 (runserver)


I develop on serveral projects at once.

If I run the runserver twice, I get this error:

System check identified no issues (0 silenced).
September 10, 2021 - 10:44:26
Django version 3.1.4, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Error: That port is already in use.

I know that I can supply a different port manually, but a more automatic approach would be nice.

How could I solve this clash without manually giving each project a port by hand?

I have more than 50 systems on my laptop, and I don't want to give them each a port number by hand.


Solution

  • You can implement something like following.

    1. Add RUN_SERVER_PORT in settings.py
    RUN_SERVER_PORT = 8080
    
    1. Implement following code in manage.py
    #!/usr/bin/env python
    """Django's command-line utility for administrative tasks."""
    import os
    import sys
    from django.core.management.commands.runserver import Command as runserver
    from django.conf import settings
    
    
    def main():
        """Run administrative tasks."""
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accountant.settings')
        try:
            from django.core.management import execute_from_command_line
        except ImportError as exc:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            ) from exc
        runserver.default_port = settings.RUN_SERVER_PORT
        execute_from_command_line(sys.argv)
    
    
    if __name__ == '__main__':
        main()
    

    Proof of Work:

    python manage.py runserver
    
    Watching for file changes with StatReloader
    Performing system checks...
    
    System check identified no issues (0 silenced).
    September 19, 2021 - 12:47:59
    Django version 3.2.6, using settings 'accountant.settings'
    Starting development server at http://127.0.0.1:8080/
    Quit the server with CONTROL-C.
    

    You can use any available port in RUN_SERVER_PORT