django change default runserver port
💻✨ Hey there tech-savvy reader! Are you tired of manually specifying the address and port every time you run the ./manage.py runserver
command in Django? 🤔 Fear not, because I'm about to drop some knowledge bombs on you that will make your life a whole lot easier! 😎🔥
🔍 So, you want to change the default port that the Django development server listens on and make it configurable in an external config.ini
file, huh? Sounds like a smart move! Let's dive in and explore some easy solutions for this common issue. 💡🔧
📝 The first thought that may come to your mind is parsing sys.argv
inside the manage.py
file and inserting the configured port, right? While that could be one way to tackle this problem, there's actually an even easier fix that doesn't require modifying Django's source code. 👌
✅ Here's a step-by-step guide to changing the default runserver port:
1️⃣ Create or locate your config.ini
file and open it.
2️⃣ Add a section called [runserver]
to the file. This section will hold the configuration options for the Django runserver.
3️⃣ Inside the [runserver]
section, add a key-value pair for the port you want to use. For example, port = 8001
.
4️⃣ Save the config.ini
file and close it.
👉 Now comes the fun part! We need to write a custom Django management command that reads the port value from the config.ini
file and passes it to the runserver command. Let's call this command runserverconfig
.
🔧 Here's an example implementation of the runserverconfig
command:
from django.conf import settings
from django.core.management.commands.runserver import Command as RunserverCommand
from configparser import ConfigParser
class Command(RunserverCommand):
def add_arguments(self, parser):
config = ConfigParser()
config.read('config.ini')
port = config.get('runserver', 'port', fallback='')
if port:
parser.add_argument('--port', default=port)
setattr(settings, 'DEFAULT_PORT', '8000')
🚀 To use this custom command and start the Django development server with the port specified in config.ini
, simply run the following command:
./manage.py runserverconfig
💡 With this setup, you can now run the server without having to manually pass the address and port each time. It will automatically use the port value specified in the config.ini
file. How convenient is that? 😄
🎉📢 Now that you know how to change the default runserver port in Django and have it configurable in an external config.ini
file, it's time to put this knowledge into action! Give it a try, and let me know in the comments below how it worked out for you. I'd love to hear about your experiences and any other cool tricks you have up your sleeves! Happy coding! 🙌💻✨