Running the Development Server in Django


Django comes with a lightweight development server that allows you to test your application during development. This guide explains how to start and use the Django development server with examples.

Step 1: Create a Django Project

If you haven’t already created a Django project, start by creating one. Run the following command in your terminal:

            django-admin startproject myproject
        

This creates a directory named myproject with the necessary files for your project.

Step 2: Navigate to Your Project Directory

Change your working directory to the project folder:

            cd myproject
        

Step 3: Run the Development Server

To start the development server, use the following command:

            python manage.py runserver
        

If the command is successful, you will see output similar to this:

            Watching for file changes with StatReloader
            Performing system checks...

            Starting development server at http://127.0.0.1:8000/
            Quit the server with CONTROL-C.
        

Open your browser and go to http://127.0.0.1:8000 to see the default Django welcome page.

Step 4: Specifying a Port Number

By default, the development server runs on port 8000. To use a different port, specify it in the command:

            python manage.py runserver 8080
        

Visit http://127.0.0.1:8080 to access the server.

Step 5: Binding to a Different IP Address

To make the server accessible on a different IP address (e.g., for testing on another device), use this command:

            python manage.py runserver 0.0.0.0:8000
        

Replace 0.0.0.0 with your machine's IP address. Devices on the same network can now access the server.

Step 6: Handling Server Logs

The development server provides logs in real time. For example:

            [27/Nov/2024 12:00:00] "GET / HTTP/1.1" 200 16384
        

This shows the HTTP request method (GET), the requested path (/), the HTTP version (1.1), the response status code (200), and the response size (16384 bytes).

Step 7: Stopping the Server

To stop the development server, press Ctrl+C in the terminal where the server is running.

Step 8: Common Issues

If you encounter the following error:

            Error: That port is already in use.
        

Use a different port number or stop the other process using the port. For example:

            python manage.py runserver 9000
        

Step 9: Limitations of the Development Server

The development server is intended for local development and testing. It is not suitable for production use due to its lack of scalability and advanced features like SSL support.

Step 10: Next Steps

Now that you know how to run the development server, you can start building and testing your Django application. Make changes to your code, refresh the browser, and see the results instantly!





Advertisement