How to Get Started with Django: A Comprehensive Guide for Beginners
Tags: python, django, webdev, website
Published: 2024-05-22 14:00:00

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?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6hb81d5cfk0pbt97v9s.png)

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](https://www.python.org/downloads/).

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.

3. **Activate the Virtual Environment:**

- On Windows:

`myenv\Scripts\activate`

- On Mac/Linux:

`source myenv/bin/activate`

4. **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.

2. **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
```

- **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.

3. **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/
```

- **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.

2. **Add the App to Your Project:** Open **_‘mysite/settings.py’_** and add **_‘blog’_** to the **_‘INSTALLED_APPS’_** list:

```
INSTALLED_APPS = [     
...     
'blog', 

]
```

---

## 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.")
```

2. **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'),
]
```

3. **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),
]
```

4. _**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
```
2. **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
```

3. **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)
```

4. **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>
```

3. **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})
```

4. **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](https://medium.com/@shaikhrayyan123/how-to-get-started-with-django-a-comprehensive-guide-for-beginners-58d305468838)