13. Creating a Django project
Django is a high-level web development framework, written in Python, that encourages fast, clean development with a pragmatic design. Creating a Django project is the first step in building web applications using this framework. This chapter will guide you step-by-step through creating a Django project from scratch.
Django Installation
Before we start creating our project, we need to ensure that Django is installed in our environment. To install Django, you can use pip, which is Python's package manager. The command to install Django is:
pip install django
After installation, you can check the Django version with the following command:
python -m django --version
Project Creation
Once we have Django installed, we can start creating our project. To create a new Django project, we use the command django-admin startproject
followed by the project name. For example, to create a project called 'myproject', we use the command:
django-admin startproject myproject
This command will create a new directory with the same name as the project, which contains the basic structure of a Django project. Inside this directory you will find a subdirectory also called 'myproject' and a file called 'manage.py'.
Project Structure
The 'manage.py' file is a command-line utility that lets you interact with the Django project in a variety of ways. The 'myproject' subdirectory is the project package, which contains four files:
__init__.py
: This is an empty file that tells Python that this directory should be considered a Python package.settings.py
: This file contains the Django project settings.urls.py
: This file contains the Django project's URL declarations.wsgi.py
: This file is an entry point for WSGI-compatible web servers to serve your project.
Running the Server
Once we've created the project, we can run the Django development server to see our project in action. For this, we first need to navigate to our project directory. Then we can use the command python manage.py runserver
to start the server:
cd myproject
python manage.py runserver
This command will start the Django development server on port 8000. If you open your browser and visit http://127.0.0.1:8000/
, you should see a welcome page. from Django, indicating that the server is working correctly.
Conclusion
Congratulations! You have successfully created your first Django project. From here, you can start adding apps to your project, creating data models, views, templates, and much more. Remember, creating the project is just the first step. Django's true power comes from its flexibility and component reuse, which allow you to build complex web applications with ease.