DJANGO
NGINX
OPEN SOURCE
ENGINEER
UPI

Building a Website with Django: A Basic Overview

Time Spent- 5m
84 Visitors

Django is a high-level Python web framework that encourages rapid development and clean design. It follows the Model-View-Template (MVT) architectural pattern.

Understanding the MVT Pattern

  • Model: Defines the structure of your data. It's typically represented by Python classes that map to database tables.
  • View: Handles the logic of processing a request and returning a response.
  • Template: Defines the presentation layer, responsible for generating HTML output.

Creating a Django Project

  1. Install Django:
pip install django
  1. Create a new project:
django-admin startproject myproject
  1. Replace myproject with your desired project name.

Creating a Django App

  1. Create an app within your project:
cd myproject
python manage.py startapp myapp
  1. Replace myapp with your app name.

Defining Models

Create models in the models.py file of your app. Models represent the data you want to store.

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)   


Creating Views

Views are Python functions that handle requests and return responses. Create views in the views.py file of your app.

Python

from django.shortcuts import render

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

Creating URLs

Define URL patterns in the urls.py file of your app.

from django.urls import path
from . import views

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


Creating Templates

Templates define the HTML structure of your pages. Create templates in the templates directory of your app.

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to my website!</h1>
</body>
</html>

Running the Development Server

python manage.py runserver

This will start a development server, and you can access your website at http://127.0.0.1:8000/.

Key Points

  • Django follows the MVT pattern for web development.
  • Models define data structures.
  • Views handle request logic.
  • Templates define the presentation layer.
  • URL patterns map URLs to views.
  • The development server is used for testing and development.

This is a basic overview.

Django offers many more features and functionalities for building complex web applications. You can explore topics like forms, authentication, database interactions, and deployment in more detail.