codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

60 / 68 topics
59Web Development with Flask60Django Framework Basics61Django ORM & Models62Django Templates & Jinja263Building REST APIs with Django Rest Framework (DRF)
Tutorials/Python Programming/Django Framework Basics
🐍Python Programming

Django Framework Basics

Updated 2026-04-20
4 min read

Django Framework Basics

Introduction

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the "batteries-included" philosophy and provides almost everything developers need right out of the box to build robust web applications. This tutorial will cover the basics of setting up a Django project, creating models, views, templates, and handling forms.

Prerequisites

Before diving into Django, ensure you have Python installed on your system. You can download it from python.org. Additionally, install pip, the package installer for Python, if it's not already included with your Python installation.

Setting Up a Django Project

Step 1: Install Django

First, you need to install Django using pip. Open your terminal or command prompt and run:

pip install django

Step 2: Create a New Django Project

Once Django is installed, create a new project by running the following command:

django-admin startproject mysite

This will create a directory named mysite with several files and directories. The most important ones are:

  • manage.py: A command-line utility that lets you interact with this Django project.
  • mysite/: The actual Python package for your project. Its name defines the namespace for your project.
    • __init__.py: An empty file that tells Python this directory should be considered a Python package.
    • settings.py: Settings/configuration for this Django project.
    • urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.
    • asgi.py and wsgi.py: Entry-points for ASGI-compatible web servers and WSGI-compatible web servers to serve your project.

Step 3: Run the Development Server

Navigate into your project directory and run the development server:

cd mysite
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 default Django welcome page.

Creating an App

In Django, a project can contain multiple apps. Each app serves a specific function. Let's create a simple app called polls.

Step 1: Create the App

Run the following command to create a new app:

python manage.py startapp polls

This will create a directory named polls with several files and directories.

Step 2: Define Models

Models in Django are Python classes that define the structure of your database tables. Open polls/models.py and add the following code:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Step 3: Register Models with the Admin Site

To manage your models through Django's admin interface, you need to register them. Open polls/admin.py and add:

from django.contrib import admin
from .models import Question, Choice

admin.site.register(Question)
admin.site.register(Choice)

Step 4: Migrate the Database

Django uses a migration system to propagate changes you make to your models into the database schema. Run the following commands:

python manage.py makemigrations polls
python manage.py migrate

This will create the necessary tables in your database.

Creating Views

Views in Django are Python functions or classes that receive web requests and return web responses. Open polls/views.py and add:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

Step 5: Configure URLs

To map a URL to this view, you need to configure the URL dispatcher. Create a file named urls.py inside the polls directory and add:

from django.urls import path
from . import views

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

Then, include the polls URLs in the project's main urls.py file. Open mysite/urls.py and modify it as follows:

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

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

Step 6: Test the View

Restart the development server if it's not already running. Visit http://127.0.0.1:8000/polls/ to see the "Hello, world. You're at the polls index." message.

Creating Templates

Templates in Django are HTML files that define the structure of your web pages. Create a directory named templates inside the polls directory and then create another directory named polls inside it. This is to avoid naming conflicts with other apps.

Inside polls/templates/polls/, create a file named index.html and add:

<!DOCTYPE html>
<html>
<head>
    <title>Polls Index</title>
</head>
<body>
    <h1>Welcome to the Polls App!</h1>
</body>
</html>

Step 7: Update the View to Use Templates

Modify polls/views.py to use the template:

from django.shortcuts import render

def index(request):
    return render(request, 'polls/index.html')

Restart the server and visit http://127.0.0.1:8000/polls/ again to see the new template.

Handling Forms

Django provides a powerful form system that can handle user input and validate it. Create a file named forms.py inside the polls directory and add:

from django import forms

class QuestionForm(forms.Form):
    question_text = forms.CharField(label='Question', max_length=200)

Step 8: Create a View to Handle Forms

Modify polls/views.py to include a form view:

from django.shortcuts import render, redirect
from .forms import QuestionForm

def add_question(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question_text = form.cleaned_data['question_text']
            # Here you would save the question to the database
            return redirect('index')
    else:
        form = QuestionForm()

    return render(request, 'polls/add_question.html', {'form': form})

Step 9: Create a Template for the Form

Create add_question.html inside polls/templates/polls/ and add:

<!DOCTYPE html>
<html>
<head>
    <title>Add Question</title>
</head>
<body>
    <h1>Add a New Question</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Step 10: Update URLs to Include the Form View

Modify polls/urls.py to include the new view:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('add/', views.add_question, name='add_question'),
]

Restart the server and visit http://127.0.0.1:8000/polls/add/ to see the form.

Conclusion

This tutorial covered the basics of setting up a Django project, creating models, views, templates, and handling forms. Django's robust framework provides a solid foundation for building complex web applications. As you continue learning, explore more advanced features like authentication, middleware, and custom management commands to enhance your projects.


PreviousWeb Development with FlaskNext Django ORM & Models

Recommended Gear

Web Development with FlaskDjango ORM & Models