search
HomeBackend DevelopmentPython TutorialDjango Unlocked: Beginners&# Spawn Point

Django Unlocked: Beginners

Introduction

Django is a powerful web framework that allows you to build robust, scalable web applications quickly and efficiently. It’s written in Python and follows the "batteries-included" philosophy, meaning it comes with a lot of built-in features that make development faster and easier, thus making it suitable for prototyping. Whether you're creating a small personal project or a large enterprise application, Django has the tools you need.

In this guide, I’ll walk you through Django’s MVT design pattern (Models, Views, and Templates), providing a solid foundation for building your own web applications. By the end, you'll have a clear understanding of how Django works and how to use its components effectively.

Setting Up a Django Project with a Virtual Environment

Refer to the official documentation of Django: Django Documentation

Before diving into the core components, let’s set up a virtual environment to manage your project’s dependencies. This helps keep your project isolated and prevents conflicts with other Python projects.

Note: I highly encourage using Linux. If you are using Windows, install WSL to access the Linux environment.

1. Install venv module:

sudo apt install python3-venv

2. Create a Virtual Environment:

python -m venv .venv

3. Activate the Virtual Environment:

source .venv/bin/activate

4. Install Django:

With the virtual environment activated, install Django:

python -m pip install django

5. Create a Django Project:

django-admin startproject myproj

Replace myproj with your desired project name.

6. Create an App:

Inside your project directory, create an app.

python manage.py startapp myapp

7. Add your newly created app to the settings.py located in:

your-project-name/your-project-name/settings.py

INSTALLED_APPS = [
    'myapp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Your project is now set up with a basic structure, including a manage.py file, project settings, and your first app

Models

Models define the structure of your database tables and the relationships between them using Python classes. Each model class maps to a single database table, and each attribute of the model corresponds to a database field. Django simplifies this process by allowing you to define your database schema using classes that inherit from django.db.models.Model.

ORM stands for Object-Relational Mapping. In Django, the ORM is a powerful feature that allows developers to interact with the database using Python code instead of writing SQL queries. This abstraction layer maps Python classes (models) to database tables and instances of those classes to rows in the table.

Introducing SQLite

Django uses SQLite as its default database because it's super easy to set up. SQLite is a lightweight database that keeps all your data in one simple file, so you don’t have to install anything extra to start saving and managing your website’s data. This makes it a great choice for development and testing, as it allows you to focus on building your application without worrying about complex database setups.

In Django, a table named Airport with attributes like 'code' and 'city' is represented as a Python class, where each attribute is defined as a class variable.

class Airport(models.Model):
    code = models.CharField(max_length=3)
    city = models.CharField(max_length=64)

1. Defining Models:

In models.py of your app, define your models using Django’s ORM.

from django.db import models

class Flight(models.Model):
    # Diri, kada flight naa tay origin kung asa gikan, destination, ug duration
    # Nakabutang sa parameters ilang properties, such as length of the characters

    origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='departures')
    destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='arrivals')
    duration = models.IntegerField()

    def __str__(self):
        return f'{self.id}: {self.origin} to {self.destination} | {self.duration} minutes.'

2. Migrations:

After defining your models, create and apply migrations to update your database schema.

In simple terms:

  • makemigrations is like planning the changes you want to make to your databse.
  • migrate is actually carrying out those changes on the database. So, after planning with makemigrations, migrate is when you execute and apply the changes.
python manage.py makemigrations
python manage.py migrate

3. Interacting with Models:

Use Django's shell to interact with your models: python manage.py shell

Example:

>> from flights.models import Flight

>> flight1 = Flight(origin="Davao", destination="Manila", duration=569)
>> fligh1.save()

I created an instance of the Flights model. This instance flight1 represents a single row in the Flight table of my database. The Flight model has fields origin, destination, and duration defined in it.
When you create the instance. you are setting these fields to specific values:

  • origin : "Davao"
  • destination : "Manila"
  • duration : 569 (representing the flight duration in minutes)

Views

Views are a crucial part of the framework that handles the logic behind what a user sees and interacts with in a web application. Views are responsible for processing user requests, retrieving necessary data from the database, and returning the appropriate response (typically an HTML page, JSON data, or a redirect).

In simple terms, Views in Django act as the middleman between the web pages and the data. They take requests from users, process any necessary data, and then send back the appropriate response, like a webpage or a file. Essentially, views decide what content should be shown to the user and how it should be presented.

In this read, we will only be using Function-Based Views

1. Function-Based Views:

These are Python functions that take a web request and return a web response. The most basic view in Django is a function that receives a request object and returns a response object.

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, World!")

2. Class-Based Views:

These are Python classes that provide more structure and allow for more complex functionality compared to Function-Based Views.

from django.views import View
from django.http import HttpResponse

class MyView(View):
    def get(self, request):
        return HttpResponse("Hello, World!")

Templates

Templates are used to render HTML and display data to users. They allow you to separate your HTML from Python code. Django templates are a powerful tool for generating dynamic HTML content in your web application. By separating the presentation (HTML) from the backend logic (Python code), templates help keep your code clean, maintainable, and reusable.

In simple terms, Templates in Django are like blueprints that define how data should be displayed on a webpage. They allow you to combine static content (like HTML) with dynamic content (like data from a database) to create a fully rendered page. Instead of hardcoding every detail, you use templates to keep the design and data separate, making it easier to update and manage your website.

1. Creating a Template

Start with creating a directory for your templates inside your app and name the directory as templates. Create another directory inside the templates named myapp.

django-proj/myapp/templates/myapp

Now, you can finally place all your templates inside the inner directory you created:

django-proj/myapp/templates/myapp/base.html

Creating the base.html allows you to define a base template or layout with common structure (headers, navbar, and footer) that other templates can inherit. This feature is useful for maintaining consistency across different pages.

Example:



    <title> {% block title %} myApp {% endblock %} </title>


    <header>
        <h1 id="My-Site">My Site</h1>
    </header>
    <div class="content">
        {% block content %}{% endblock %}
    </div>
    <footer>
        <p>Footer content here</p>
    </footer>


Let's create another template called index.html and place it in the same directory of base.html.

Example of extending template index.html:

{% extends "myapp/base.html" %}
{% block content %}
    <h1 id="Flights">Flights</h1>
    
    {% for flight in flights %}
  • Flight: {{ flight.id }} {{ flight.origin }} to {{ flight.destination }}
  • {% endfor %}
{% endblock %}

The {% extends "myapp/base.html" %} tells Django to use the base.html as the base layout template. The {% block content %} defines a block of content that will be filled with content from index.html. The content block in base.html will be replaced with the content provided in index.html.

2. Rendering Templates

In a Django view, you typically render a template using the render() function, which combines the template with the context data to produce the final HTML output.

from django.shortcuts import render

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

When Django renders index.html, it will include the structure from base.html, replacing the content block with the content specified in index.html. This allows for consistent design across pages and makes it easy to update the overall layout without changing every individual template.

URLs and Routing

Django uses URL patterns to map URLs to views. These patterns are defined in a file called urls.py within each Django app.

URL patterns are defined with the path() function, mapping specific URL paths to view functions or classes. Dynamic URL segments, such as , allow for capturing variables from the URL to be used in views. The include() function enables modular URL management by including patterns from other apps.

In simple terms, URLs are like street addresses for different pages on your website. Routing is the system that makes sure when someone types in a specific address (URL), they get directed to the right page. You set up these "addresses" in a special file so Django knows where to send people when they visit your site.

1. Configuring URLs:
Define URL patterns in urls.py of your app:

from django.urls import path
from . import views

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

Inlcude your app's URLs in the project's urls.py:

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

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

Wrapping up

Congratulations! You've taken the first steps in learning Django. I’ve covered the basics of Models, Views, Templates, and URL routing. With these fundamentals, you’re on your way to building your own Django applications. Keep experimenting, keep coding, and don't hesitate to dive deeper into the Django documentation and community resources.

I hope this guide has made these concepts clearer and that you’ve learned something valuable along the way.

  • 0xshr00msz

The above is the detailed content of Django Unlocked: Beginners&# Spawn Point. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

Explain the purpose of virtual environments in Python.Explain the purpose of virtual environments in Python.Mar 19, 2025 pm 02:27 PM

The article discusses the role of virtual environments in Python, focusing on managing project dependencies and avoiding conflicts. It details their creation, activation, and benefits in improving project management and reducing dependency issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use