Setting up a Django project and creating a virtual environment are crucial first steps in your Django development journey. In this blog post, we'll walk through the process step-by-step, ensuring you have a solid foundation for your Django projects.
Before we dive in, let's quickly discuss why virtual environments are important:
Let's start by creating a virtual environment for our Django project:
cd /path/to/your/project
python -m venv myenv
myenv\Scripts\activate
source myenv/bin/activate
You'll notice your terminal prompt change, indicating that the virtual environment is active.
Now that we have our virtual environment set up, let's install Django:
pip install django
This command installs the latest version of Django. If you need a specific version, you can specify it like this:
pip install django==3.2.4
With Django installed, we can create our project:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Let's take a look at the project structure Django has created for us:
myproject/
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── myapp/
├── __init__.py
├── admin.py
├── apps.py
├── migrations/
├── models.py
├── tests.py
└── views.py
manage.py
: A command-line utility for interacting with your Django project.myproject/
: The project's Python package, containing settings and configuration.myapp/
: Your newly created app, where you'll build your application logic.myproject/settings.py
and add your app to the INSTALLED_APPS
list:INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # Add your app here ]
settings.py
. By default, Django uses SQLite, which is great for development:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }
Now that we've set everything up, let's run our Django development server:
python manage.py runserver
Visit http://127.0.0.1:8000/
in your web browser, and you should see the Django welcome page!
To keep track of your project dependencies, create a requirements.txt
file:
pip freeze > requirements.txt
This file lists all installed packages and their versions, making it easy to recreate your environment later.
requirements.txt
file up to date.08/11/2024 | Python
06/10/2024 | Python
17/11/2024 | Python
08/12/2024 | Python
08/11/2024 | Python
08/12/2024 | Python
25/09/2024 | Python
15/10/2024 | Python
15/10/2024 | Python
15/10/2024 | Python
15/11/2024 | Python
15/11/2024 | Python