Dec. 19, 2024
If you’re starting your journey in web development and have decided to use Django, you’ve made an excellent choice. Django is a powerful, Python-based web framework that simplifies the development process and helps you create robust, scalable applications. This guide will walk you through setting up Django from scratch.
Before diving into Django, make sure you have the following prerequisites:
If Python isn’t installed on your machine:
brew
for macOS or apt
for Linux) to install it.Verify the installation by running:
A virtual environment helps keep your Django project dependencies separate. To create one:
Open your terminal and navigate to the directory where you want to set up your project.
Run the following command to create a virtual environment:
Replace myenv
with a name for your environment.
Activate the virtual environment:
Once activated, your terminal will show the virtual environment’s name, e.g., (myenv)
.
With the virtual environment activated, install Django using pip:
You can verify the installation by checking the Django version:
Run the following command to create a new project:
Replace myproject
with the name of your project.
Navigate into your project directory:
To ensure everything is set up correctly, run the Django development server:
Open a browser and go to http://127.0.0.1:8000/
. You should see Django’s default welcome page, confirming your setup is complete.
Django projects are composed of one or more apps. To create your first app:
Run:
Replace myapp
with the name of your app.
Register the app in your project by adding it to the INSTALLED_APPS
list in myproject/settings.py
:
Django comes pre-configured with SQLite, but you can connect to other databases like PostgreSQL or MySQL. For now, let’s use SQLite:
Apply migrations to set up the default database schema:
Create a superuser to access the admin panel:
Follow the prompts to set a username, email, and password.
Run the development server again and visit http://127.0.0.1:8000/admin/
to access the admin panel.
Let’s create a simple view:
Open myapp/views.py
and add:
Map the view to a URL. In myapp/urls.py
(create this file if it doesn’t exist), add:
Link your app’s URLs to the project. In myproject/urls.py
, add:
Visit http://127.0.0.1:8000/
, and you’ll see “Hello, Django!” displayed in your browser.
Congratulations! You’ve set up Django from scratch and created your first view. From here, you can start building more complex applications by exploring Django’s features like templates, models, and forms. Django’s extensive documentation and active community make it easy to learn and grow as a developer.
Ready to build something amazing? Start experimenting with Django today!