”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 解锁姜戈:初学者&# 生成点

解锁姜戈:初学者&# 生成点

发布于2024-08-23
浏览:459

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:



     {% block title %} myApp {% endblock %} 

My Site

{% block content %}{% endblock %}

Footer content here

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 %}
    

Flights

    {% 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
版本声明 本文转载于:https://dev.to/0xshr00msz/django-unlocked-beginners-spawn-point-5g5e?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 优化 AWS ECS 的 Java 堆设置
    优化 AWS ECS 的 Java 堆设置
    我们在 AWS Elastic Container Service(ECS) Fargate 上运行多个 Java 服务 (Corretto JDK21)。每个服务都有自己的容器,我们希望使用为每个进程支付的所有可能的资源。但这些步骤可以应用于 EC2 和其他云。 服务正在运行批处理作业,延迟并不重...
    编程 发布于2024-11-06
  • PHP 初学者必备知识:释放网站的全部潜力
    PHP 初学者必备知识:释放网站的全部潜力
    PHP基础知识:释放网站潜能简介PHP是一种强大的服务器端脚本语言,广泛用于创建动态网站。对于初学者来说,掌握PHP基础知识至关重要。本文将提供一个全面的指南,涵盖PHP编程的基本要素,并通过实战案例巩固理解。安装并配置PHP要开始使用PHP,您需要安装PHP解释器和相关的软件。遵循以下步骤:- 下...
    编程 发布于2024-11-06
  • 如何确定 PHP 标头的正确图像内容类型?
    如何确定 PHP 标头的正确图像内容类型?
    确定 PHP 标头的图像内容类型使用 Header() 函数从 Web 根目录之外显示图像时,用户可能会遇到困惑关于指定的内容类型:image/png。然而,尽管内容类型固定,但具有各种扩展名的图像(例如, JPG、GIF)仍然可以成功显示。要解决这种差异,动态确定正确的扩展名至关重要基于文件扩展名...
    编程 发布于2024-11-05
  • ByteBuddies:使用 Python 和 Tkinter 创建交互式动画宠物
    ByteBuddies:使用 Python 和 Tkinter 创建交互式动画宠物
    大家好! 我很高兴向大家介绍 ByteBuddies,这是一个用 Python 和 Tkinter 创建的个人项目,展示了交互式动画虚拟宠物。 ByteBuddies 将引人入胜的动画与用户交互相结合,提供了展示 GUI 编程强大功能的独特体验。该项目旨在通过提供交互式虚拟宠物来让您的屏幕充满活力...
    编程 发布于2024-11-05
  • 如何解决“TypeError:\'str\'对象不支持项目分配”错误?
    如何解决“TypeError:\'str\'对象不支持项目分配”错误?
    'str'对象项分配错误疑难解答尝试在 Python 中修改字符串中的特定字符时,您可能会遇到错误“类型错误:“str”对象不支持项目分配。”发生这种情况是因为 Python 中的字符串是不可变的,这意味着它们无法就地更改。解决此问题的一种常见方法是将字符串转换为可变列表,进行必要的...
    编程 发布于2024-11-05
  • 如何缓解 GenAI 代码和 LLM 集成中的安全问题
    如何缓解 GenAI 代码和 LLM 集成中的安全问题
    GitHub Copilot and other AI coding tools have transformed how we write code and promise a leap in developer productivity. But they also introduce new ...
    编程 发布于2024-11-05
  • Spring 中的 ContextLoaderListener:必要的邪恶还是不必要的复杂?
    Spring 中的 ContextLoaderListener:必要的邪恶还是不必要的复杂?
    ContextLoaderListener:必要的邪恶还是不必要的复杂?开发人员经常遇到在 Spring Web 应用程序中使用 ContextLoaderListener 和 DispatcherServlet。然而,一个令人烦恼的问题出现了:为什么不简单地使用 DispatcherServlet...
    编程 发布于2024-11-05
  • JavaScript 机器学习入门:TensorFlow.js 初学者指南
    JavaScript 机器学习入门:TensorFlow.js 初学者指南
    机器学习 (ML) 迅速改变了软件开发世界。直到最近,得益于 TensorFlow 和 PyTorch 等库,Python 仍是 ML 领域的主导语言。但随着 TensorFlow.js 的兴起,JavaScript 开发人员现在可以深入令人兴奋的机器学习世界,使用熟悉的语法直接在浏览器或 Node...
    编程 发布于2024-11-05
  • extjs API 查询参数示例
    extjs API 查询参数示例
    API 查询 参数是附加到 API 请求 URL 的键值对,用于向服务器发送附加信息。它们允许客户端(例如 Web 浏览器或应用程序)在向服务器发出请求时指定某些条件或传递数据。 查询参数添加到 URL 末尾问号 (?) 后。每个参数都是一个键值对,键和值之间用等号 (=) 分隔。如果有多个查询参数...
    编程 发布于2024-11-05
  • 如何解决Go中从不同包导入Proto文件时出现“Missing Method Protoreflect”错误?
    如何解决Go中从不同包导入Proto文件时出现“Missing Method Protoreflect”错误?
    如何从不同的包导入 Proto 文件而不遇到“Missing Method Protoreflect”错误在 Go 中,protobuf 常用于数据序列化。将 protobuf 组织到不同的包中时,可能会遇到与缺少 ProtoReflect 方法相关的错误。当尝试将数据解组到单独包中定义的自定义 p...
    编程 发布于2024-11-05
  • 为什么MySQL在查询“Field = 0”非数字数据时返回所有行?
    为什么MySQL在查询“Field = 0”非数字数据时返回所有行?
    不明确的查询:理解为什么 MySQL 返回“Field=0”的所有行在 MySQL 查询领域,一个看似无害的比较,例如“SELECT * FROM table WHERE email=0”,可能会产生意外的结果。它没有按预期过滤特定行,而是返回表中的所有记录,从而引发了对数据安全性和查询完整性的担忧...
    编程 发布于2024-11-05
  • 服务器发送事件 (SSE) 的工作原理
    服务器发送事件 (SSE) 的工作原理
    SSE(服务器发送事件)在 Web 开发领域并未广泛使用,本文将深入探讨 SSE 是什么、它是如何工作的以及它如何受益您的申请。 什么是上交所? SSE 是一种通过 HTTP 连接从服务器向客户端发送实时更新的简单而有效的方法。它是 HTML5 规范的一部分,并受到所有现代 Web ...
    编程 发布于2024-11-05
  • 如何从字符串 TraceID 创建 OpenTelemetry Span?
    如何从字符串 TraceID 创建 OpenTelemetry Span?
    从字符串 TraceID 构造 OpenTelemetry Span要建立 Span 之间的父子关系,必须在上下文传播不可行的情况下使用标头。在这种情况下,跟踪 ID 和跨度 ID 包含在消息代理的标头中,这允许订阅者使用父跟踪 ID 创建新的跨度。解决方案以下步骤可以使用跟踪 ID 在订阅者端构建...
    编程 发布于2024-11-05
  • 如何在gRPC中实现服务器到客户端的广播?
    如何在gRPC中实现服务器到客户端的广播?
    gRPC 中的广播:服务器到客户端通信建立 gRPC 连接时,通常需要将事件或更新从服务器广播到客户端连接的客户端。为了实现这一点,可以采用各种方法。Stream Observables一种常见的方法是利用服务器端流。每个连接的客户端都与服务器建立自己的流。然而,直接订阅其他服务器客户端流是不可行的...
    编程 发布于2024-11-05
  • 为什么填充在 Safari 和 IE 选择列表中不起作用?
    为什么填充在 Safari 和 IE 选择列表中不起作用?
    在 Safari 和 IE 的选择列表中不显示填充尽管 W3 规范中没有限制,但 WebKit 浏览器不支持选择框中的填充,包括Safari 和 Chrome。因此,这些浏览器中不应用填充。要解决此问题,请考虑使用 text-indent 而不是 padding-left。通过相应增加选择框的宽度来...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3