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

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

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

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]删除
最新教程 更多>
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式界面中实现垂直滚动元素的CSS高度限制 考虑一个布局,其中我们具有与可滚动的映射div一起移动的subollable map div用户的垂直滚动,同时保持其与固定侧边栏的对齐方式。但是,地图的滚动无限期扩展,超过了视口的高度,阻止用户访问页面页脚。 可以限制地图的滚动,我们可以利用CSS...
    编程 发布于2025-02-19
  • 如何在Java字符串中有效替换多个子字符串?
    如何在Java字符串中有效替换多个子字符串?
    Exploiting Regular ExpressionsA more efficient solution involves leveraging regular expressions.正则表达式允许您定义复杂的搜索模式并在单个操作中执行文本转换。示例使用接下来,您可以使用匹配器查找令牌的所...
    编程 发布于2025-02-19
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction: connect to to to Database connect to t...
    编程 发布于2025-02-19
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 //错误:“ cance redeclare foo()” 但是,PHP工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地重新定义...
    编程 发布于2025-02-19
  • PHP阵列键值异常:了解07和08的好奇情况
    PHP阵列键值异常:了解07和08的好奇情况
    PHP数组键值问题,使用07&08 在给定数月的数组中,键值07和08呈现令人困惑的行为时,就会出现一个不寻常的问题。运行print_r($月份)返回意外结果:键“ 07”丢失,而键“ 08”分配给了9月的值。此问题源于PHP对领先零的解释。当一个数字带有0(例如07或08)的前缀时,PHP将...
    编程 发布于2025-02-19
  • 如何使用PHP将斑点(图像)正确插入MySQL?
    如何使用PHP将斑点(图像)正确插入MySQL?
    在尝试将image存储在mysql数据库中时,您可能会遇到一个可能会遇到问题。本指南将提供成功存储您的图像数据的解决方案。 essue values('$ this-> image_id','file_get_contents($ tmp_image)&#...
    编程 发布于2025-02-19
  • 如何为PostgreSQL中的每个唯一标识符有效地检索最后一行?
    如何为PostgreSQL中的每个唯一标识符有效地检索最后一行?
    [2最后一行与数据集中的每个不同标识符关联。考虑以下数据: 1 2014-02-01 kjkj 1 2014-03-11 ajskj 3 2014-02-01 sfdg 3 2014-06-12 fdsa 为了检索数据集中每个唯一ID的最后一行信息,您可以在操作员上使用Postgres的有效效...
    编程 发布于2025-02-19
  • 如何可靠地检查MySQL表中的列存在?
    如何可靠地检查MySQL表中的列存在?
    在mySQL中确定列中的列存在,验证表中的列存在与与之相比有点困惑其他数据库系统。常用的方法:如果存在(从信息_schema.columns select * * where table_name ='prefix_topic'和column_name =&...
    编程 发布于2025-02-19
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在默认值中使用current_timestamp或mysql版本中的current_timestamp或在5.6.5 这种限制源于遗产实现的关注,这些限制需要为Current_timestamp功能提供特定的实现。消息和相关问题 current_timestamp值: 创建表`foo`( `...
    编程 发布于2025-02-19
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    [2明确担心Microsoft Visual C(MSVC)在正确实现两相模板实例化方面努力努力。该机制的哪些具体方面无法按预期运行?背景:说明:的初始Syntax检查在范围中受到限制。它未能检查是否存在声明名称的存在,导致名称缺乏正确的声明时会导致编译问题。为了说明这一点,请考虑以下示例:一个符合...
    编程 发布于2025-02-19
  • Java是否允许多种返回类型:仔细研究通用方法?
    Java是否允许多种返回类型:仔细研究通用方法?
    在java中的多个返回类型:一个误解介绍,其中foo是自定义类。该方法声明似乎拥有两种返回类型:列表和E。但是,情况确实如此吗?通用方法:拆开神秘 [方法仅具有单一的返回类型。相反,它采用机制,如钻石符号“ ”。分解方法签名: :本节定义了一个通用类型参数,E。它表示该方法接受扩展FOO类的任何...
    编程 发布于2025-02-19
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 问题:考虑以下CSS和HTML: position:fixed; grid-template-columns:40%60%; grid-gap:5px; 背景:#eee; 当位置未固定时,网格将正确显示。但是,当...
    编程 发布于2025-02-19
  • 在没有密码提示的情况下,如何在Ubuntu上安装MySQL?
    在没有密码提示的情况下,如何在Ubuntu上安装MySQL?
    在ubuntu 使用debconf-set-selections 在安装过程中避免密码提示mysql root用户。这需要以下步骤: sudo debconf-set-selections
    编程 发布于2025-02-19
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mysql组使用mysql组来调整查询结果。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的基于列的转换。通过子句以及条件汇总函数,例如总和或情况。让我们考虑以下查询: select d.data_timestamp, sum(data_id = 1 tata...
    编程 发布于2025-02-19
  • \“(1)vs.(;;):编译器优化是否消除了性能差异?\”
    \“(1)vs.(;;):编译器优化是否消除了性能差异?\”
    答案:在大多数现代编译器中,while(1)和(1)和(;;)之间没有性能差异。 说明: perl: S-> 7 8 unstack v-> 4 -e语法ok 在GCC中,两者都循环到相同的汇编代码中,如下所示:。 globl t_时 t_时: .l2: movl $ .lc0,�i ...
    编程 发布于2025-02-19

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

Copyright© 2022 湘ICP备2022001581号-3