Django 是一个强大的 Web 框架,可让您快速高效地构建健壮、可扩展的 Web 应用程序。它是用 Python 编写的,遵循“包含电池” 理念,这意味着它具有许多内置功能,可以使开发更快、更轻松,从而适合原型设计。 无论您是创建小型个人项目还是大型企业应用程序,Django 都有您需要的工具。
在本指南中,我将引导您了解 Django 的 MVT 设计模式(模型、视图和模板),为构建您自己的 Web 应用程序提供坚实的基础。最后,您将清楚地了解 Django 的工作原理以及如何有效地使用其组件。
参考Django的官方文档:Django Documentation
在深入研究核心组件之前,让我们设置一个虚拟环境来管理项目的依赖项。这有助于保持您的项目隔离并防止与其他 Python 项目发生冲突。
注意:我强烈鼓励使用Linux。如果您使用的是Windows,请安装WSL以访问Linux环境。
sudo apt install python3-venv
python -m venv .venv
source .venv/bin/activate
激活虚拟环境后,安装Django:
python -m pip install django
django-admin startproject myproj
将 myproj 替换为您想要的项目名称。
在您的项目目录中,创建一个应用程序。
python manage.py startapp myapp
您的项目名称/您的项目名称/settings.py
INSTALLED_APPS = [ 'myapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
您的项目现在已经设置了基本结构,包括管理.py 文件、项目设置和您的第一个应用程序
模型 使用 Python 类定义数据库表的结构以及它们之间的关系。每个模型类映射到一个数据库表,模型的每个属性对应一个数据库字段。 Django 允许您使用继承自 django.db.models.Model 的类来定义数据库模式,从而简化了此过程。
ORM 代表对象关系映射。在 Django 中,ORM 是一个强大的功能,它允许开发人员使用 Python 代码而不是编写 SQL 查询来与数据库交互。该抽象层将 Python 类(模型)映射到数据库表,并将这些类的实例映射到表中的行。
Django 使用 SQLite 作为默认数据库,因为它非常容易设置。 SQLite 是一种轻量级数据库,它将所有数据保存在一个简单的文件中,因此您无需安装任何额外的内容即可开始保存和管理网站的数据。这使其成为开发和测试的绝佳选择,因为它使您可以专注于构建应用程序,而不必担心复杂的数据库设置。
在 Django 中,一个名为 Airport 的表,具有“code”和“city”等属性,被表示为一个 Python 类,其中每个属性都定义为一个类变量。
class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64)
在应用程序的 models.py 中,使用 Django 的 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.'
定义模型后,创建并应用迁移以更新数据库架构。
简单来说:
python manage.py makemigrations python manage.py migrate
使用 Django 的 shell 与您的模型交互:python manage.py shell
示例:
>> from flights.models import Flight >> flight1 = Flight(origin="Davao", destination="Manila", duration=569) >> fligh1.save()
我创建了 Flights 模型的一个实例。此实例 Flight1 代表我的数据库的 Flight 表中的一行。 Flight 模型中定义了出发地、目的地和持续时间字段。
当您创建实例时。您正在将这些字段设置为特定值:
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
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!")
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 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.
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:
<!DOCTYPE html> <html> <head> <title> {% block title %} myApp {% endblock %} </title> </head> <body> <header> <h1>My Site</h1> </header> <div class="content"> {% block content %}{% endblock %} </div> <footer> <p>Footer content here</p> </footer> </body> </html>
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>Flights</h1> <ul> {% for flight in flights %} <li>Flight: {{ flight.id }} {{ flight.origin }} to {{ flight.destination }}</li> {% endfor %} </ul> {% 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.
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.
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
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')) ]
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.
以上是解锁姜戈:初学者 生成点的详细内容。更多信息请关注PHP中文网其他相关文章!