DEV Community

Cover image for How to Get Started with Django: A Comprehensive Guide for Beginners
Rayyan Shaikh
Rayyan Shaikh

Posted on • Originally published at Medium

How to Get Started with Django: A Comprehensive Guide for Beginners

Ever wondered how websites are built? Well, wonder no more because I’m about to take you on an exciting journey into developing a website using Django — a powerful framework of Python for creating awesome websites!

In this easy-to-follow guide, I’ll take you by the hand and show you everything you need to know to get started with Django.

So, get ready to dive into the world of Django with me! We’ll learn step by step, and by the end of this guide, you’ll be on your way to building your websites. Let’s go!


What is Django, and Why Should You Use It?

What is Django, and Why Should You Use It?

Imagine you want to build a treehouse. You could gather wood, nails, and tools from various places or buy a complete treehouse kit with everything you need. Django is like that treehouse kit for web development. It provides a complete toolkit to build web applications, including:

  • An admin panel for managing your site
  • Built-in authentication for user management
  • A powerful ORM (Object-Relational Mapping) for database interactions
  • A templating engine for generating HTML

Django follows the “batteries-included” philosophy, meaning it comes with most of the things you need to get started right out of the box.


Setting Up Your Django Environment

Before we dive into coding, let’s get your environment set up. Here’s what you need to do:

  1. Install Python: Make sure you have Python installed on your computer. Django works with Python, so this is a must. If not here is the link to Python versions.

  2. Create a Virtual Environment: This is like a sandbox for your project, ensuring that dependencies for different projects don’t interfere. Open your terminal and run:

python -m venv myenv

Replace ‘myenv’ with whatever name you prefer for your environment.

  1. Activate the Virtual Environment:
  • On Windows:

myenv\Scripts\activate

  • On Mac/Linux:

source myenv/bin/activate

  1. Install Django: Now that your virtual environment is active, install Django by running:

pip install django


Creating Your First Django Project

Now that Django is installed, let’s create your first project. Think of a Django project as a container for your website. Here’s how to set it up:

  1. Start a Project: Run the following command in your terminal:

django-admin startproject mysite

This creates a new directory called 'myenv' with the basic structure of a Django project.

  1. Understand the Project Structure: Navigate into the ‘myenv’ directory:

cd mysite

You’ll see something like this:

mysite/     
  manage.py     
  mysite/         
    __init__.py         
    settings.py         
    urls.py         
    wsgi.py
Enter fullscreen mode Exit fullscreen mode
  • manage.py: A command-line utility for managing your project.
  • settings.py: Configuration settings for your project.
  • urls.py: URL declarations for your project; it’s like a table of contents.
  • wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.
  1. Run the Development Server: To see your project in action, run:

python manage.py runserver

Open your web browser and go to http://127.0.0.1:8000/’. You should see the “Welcome to Django” page. Congrats, you’ve just started your first Django project!


Creating a Django App

A Django project can contain multiple apps. An app is a web application that does something — for example, a blog, a forum, or a poll. Let’s create a simple app called “blog”.

  1. Start an App: Run this command inside your project directory:

python manage.py startapp blog

This creates a “blog” directory with the following structure:

blog/
    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
    migrations/
Enter fullscreen mode Exit fullscreen mode
  • models.py: Define your database models here.
  • views.py: Handle the logic for your web pages here.
  • admin.py: Register your models with the Django admin site here.
  1. Add the App to Your Project: Open ‘mysite/settings.py’ and add ‘blog’ to the ‘INSTALLED_APPS’ list:
INSTALLED_APPS = [     
...     
'blog', 

]
Enter fullscreen mode Exit fullscreen mode

Creating a First View

A view is a function that takes a web request and returns a web response. Let’s create a simple view in ‘blog/views.py’.

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the blog index.")
Enter fullscreen mode Exit fullscreen mode
  1. Map the View to a URL: Open ‘blog/urls.py’ (you might need to create this file) and add:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
Enter fullscreen mode Exit fullscreen mode
  1. Include the App’s URLconf in the Project’s URLconf: Open ‘mysite/urls.py’ and modify it to include your blog app’s URLs:
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
]
Enter fullscreen mode Exit fullscreen mode
  1. Check Your Work: Run the development server again:

python manage.py runserver

Go to http://127.0.0.1:8000/blog/’. You should see “Hello, world. You're at the blog index.” Awesome, your first Django view is live!]


Working with Models

Models are where Django stores your data. They are Python classes that map to database tables. Let’s create a simple model for a blog post.

  1. Define a Model: Open ‘blog/models.py’ and add:
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode
  1. Create and Apply Migrations: Django uses migrations to propagate changes you make to your models into your database schema. Run:
python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
  1. Register the Model with Admin: Open ‘blog/admin.py’ and register your model:
from django.contrib import admin
from .models import Post

admin.site.register(Post)
Enter fullscreen mode Exit fullscreen mode
  1. Use the Admin Interface: Run the server and go to http://127.0.0.1:8000/admin/’. Log in with the superuser account you created earlier, and you’ll see the Posts section where you can add, edit, and delete posts.

Creating Templates

Templates control how data is displayed. Let’s create a template for displaying a list of blog posts.

  1. Create a Template Directory: Create a directory named ‘templates’ inside the ‘blog’ app directory. Inside ‘templates’, create another directory named ‘blog’.
  2. Create a Template File: Create a file named ‘index.html’ inside ‘blog/templates/blog’ and add:
<!DOCTYPE html>
<html>
<head>
    <title>Blog</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <ul>
        {% for post in posts %}
        <li>{{ post.title }} - {{ post.created_at }}</li>
        {% endfor %}
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Modify the View to Use the Template: Open ‘blog/views.py’ and modify the ‘index’ view:
from django.shortcuts import render
from .models import Post

def index(request):
    posts = Post.objects.all()
    return render(request, 'blog/index.html', {'posts': posts})
Enter fullscreen mode Exit fullscreen mode
  1. Check the Template: Run the server and go to http://127.0.0.1:8000/blog/’. You should see a list of blog posts displayed using your template.

Wrap Up

And there you have it! You’ve set up Django, created a project and an app, written your first view, worked with models, and created templates. This is just the beginning of your Django journey. From here, you can start exploring more advanced features like forms, user authentication, and deploying your Django project.

Django makes web development fun and efficient. With its robust framework and “batteries-included” philosophy, you have all the tools you need to build amazing web applications. So keep experimenting, keep building and happy coding!

Originally published on Medium: https://medium.com/@shaikhrayyan123/how-to-get-started-with-django-a-comprehensive-guide-for-beginners-58d305468838

Top comments (0)