Skip to main content

Command Palette

Search for a command to run...

Getting Started with Django: A Comprehensive Guide to Your First App

From Basic Setup to Advanced Tips for Efficient Django Development

Updated
3 min read
Getting Started with Django: A Comprehensive Guide to Your First App
A

Experienced Software Engineer proficient in Python, Django, ReactJS, and Next.js, with expertise in web scraping. Dedicated to developing robust web applications, I specialize in integrating cutting-edge technologies to innovate and optimize efficiency.

Setting up and creating your first Django app is a foundational step in web development with Django. This guide will take you through the process from installation to creating a basic app, including advanced tips to enhance your development workflow.

Prerequisites

  • Python 3.6 or higher

  • pip (Python package installer)

  • Virtual environment management tool (optional but recommended)

Step 1: Install Django

First, ensure you have Python installed. Check your Python version:

python --version

Next, install Django using pip:

pip install django

Verify the installation:

django-admin --version

Create a virtual environment to isolate your project dependencies:

python -m venv myenv

Activate the virtual environment:

  • On Windows:

      myenv\Scripts\activate
    
  • On macOS/Linux:

      source myenv/bin/activate
    

Step 3: Create a Django Project

Use django-admin to start a new project. Replace myproject with your project name:

django-admin startproject myproject
cd myproject

Step 4: Create a Django App

Inside your project directory, create a new app. Replace myapp with your app name:

python manage.py startapp myapp

Step 5: Configure the Project Settings

Open myproject/settings.py and add your new app to the INSTALLED_APPS list:

INSTALLED_APPS = [
    # Default apps...
    'myapp',
]

Step 6: Create a Simple View

In your app directory (myapp), open views.py and create a basic view:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, world! This is my first Django app.")

Step 7: Map the View to a URL

Create a new file called urls.py in your app directory (myapp):

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

Include your app's URLs in the project's URL configuration. Open myproject/urls.py and modify it:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

Step 8: Run the Development Server

Run the development server to see your app in action:

python manage.py runserver

Open your web browser and navigate to http://127.0.0.1:8000/. You should see "Hello, world! This is my first Django app."

Advanced Tips

1. Using Class-Based Views

Class-based views (CBVs) provide more structure and reusability. Here’s how to convert your view to a CBV:

In views.py:

from django.views import View

class HomeView(View):
    def get(self, request):
        return HttpResponse("Hello, world! This is my first Django app using a class-based view.")

In urls.py:

from django.urls import path
from .views import HomeView

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
]

2. Template System

Instead of returning raw HTML, use Django’s templating system. Create a templates directory inside myapp and a file called home.html:

myapp/templates/home.html:

<!DOCTYPE html>
<html>
<head>
    <title>My First Django App</title>
</head>
<body>
    <h1>Hello, world! This is my first Django app.</h1>
</body>
</html>

Modify the view to render this template:

In views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

3. Models and Database

Django's ORM (Object-Relational Mapping) allows you to interact with your database using Python classes. Define models in models.py:

myapp/models.py:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title

Apply the model changes to the database:

epython manage.py makemigrations
python manage.py migrate

Use the Django admin interface to manage your models. Register your model in admin.py:

myapp/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Create a superuser to access the admin:

python manage.py createsuperuser

Start the server and navigate to http://127.0.0.1:8000/admin to log in with your superuser credentials.

Conclusion

You’ve now set up a Django project, created an app, and explored basic and advanced concepts. This foundational knowledge will enable you to build more complex applications. Remember to refer to the Django documentation for more detailed information and best practices.

Django

Part 1 of 1

In this series i will discuss about Django and Django Rest Framework.