Creating a Django project with a virtual environment (venv) and running it is a fundamental task for setting up your Django development environment.
Install Python and pip
Ensure that Python and pip
are installed on your system. You can check if they are installed by running
python --version # or python3 --version pip --version # OR pip3 --version
If they are not installed, download and install them from python.org.
Create a Virtual Environment
Navigate to the directory where you want to create your project and run.
python -m venv myprojectenv
Replace myprojectenv
with your preferred virtual environment name.
Activate the Virtual Environment
Activate the virtual environment using the following command-
- windows
myprojectenv\Scripts\activate
- macOS/Linux
source myprojectenv/bin/activate
Install Django
With the virtual environment activated, install Django using pip -
pip install django
Create a Django Project
Create a new Django project by running -
django-admin startproject myproject
Replace myproject
with your desired project name.
Navigate to the Project Directory
Change directory to the project directory-
cd myproject
Make Migrations
Create initial migrations for your models by running
python manage.py makemigrations
Apply Migrations
Apply the migrations to your database
python manage.py migrate
Run the Development Server
Run the Django development server to verify the setup
python manage.py runserver
You should see output indicating that the server is running. Open a web browser and go to http://127.0.0.1:8000/
to see the Django welcome page.
Deactivate the Virtual Environment
When you are done, deactivate the virtual environment by running
deactivate
By following these steps, you should have a working Django project running in a virtual environment.