Django 快速入门 Todo 案例
什么是 Django
Django
是一个模仿 MTV 框架的 Web 应用程序框架。它最初是为需要快速开发的新闻网站而设计的,目的是让网站开发变得简单、快速。
第一次使用 Django
关于 在终端中输入命令,在当前目录中创建 Django 的分步教程
制作一个 待办事项列表♾♾♾Django 这是门框开始。在阅读本文之前,你应该了解
配置和应用程序配置。 Python
的基本语法,否则可能会有点不知所措。 创建新项目
django
项目,其中包含项目实例所需的设置集合,包括数据库配置。 Django
django-admin startproject mysite
复制代码
启动项目
切换到当前目录mysite
并输入命令在本地8000
端口上打开站点服务。
python manage.py runserver
复制代码
创建TodoList应用程序
这里的应用程序可以理解功能划分,上面创建的项目是一个多功能网站。
python manage.py startapp todolist
复制代码
在 如果想使用其他数据库,需要安装相应的数据库驱动,并在工程配置文件的DATABASES部分进行更改。 ,我们的应用程序需要一个 每个类代表一个模型,下面的类变量是模型的各个字段 定义完模型后,我们需要告诉 执行上述命令后,可以看到 对于应用程序 / 、、 注意。我们在 在项目中,要引用应用程序中的路由信息,我们其实可以直接将路径写在文件下,但是随着使用的应用程序越来越多,文件会变得越来越大,难以管理。 ?本例中, template 上面的代码是 然后我们需要编写三个方法 在视图 使用 定义 以下两个方法用于在数据库中添加和删除数据。 此时,应用程序 当然,这只是INSTALLED_APPS
属性下引用项目中的应用程序mysite/settings.py。 ,通知
django
新todolist
应用程序已添加到当前项目。 ?好方法。 TodoList
模型来存储事件标题、创建和更新时间。 // todolist/models.py
from django.db import models
# Create your models here.
class TodoList(models.Model):
def __str__(self) -> str:
return self.title
title = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
复制代码
django
为我们创建合适的表。// 检测模型变化,将修改部分储存起来
python manage.py makemigrations todolist
// 自动执行数据库迁移,同步数据库结构
python manage.py migrate
复制代码
django
已自动在db.sqlite3创建❀路由
文件夹中。当我们在这个项目中请求一个地址时,♓创建
urls.py
位于todolistdjango
会迭代每条路由的地址,直到匹配为止,直到当前请求的url
匹配为止。 (如果不匹配会抛出异常) // todolist/urls.py
from django.urls import path
from . import views
app_name = "todolist"
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('add', views.add, name='add'),
path('delete', views.delete, name='delete')
]
复制代码
todolist
,我们创建了三个路由地址,分别是/
删除
,对应列表页(主页),添加、删除数据。 views.py
下引用了该方法。由于views.py文件中没有配置合适的方法,导致页面无法正常显示。 django
在template
/ index中找到对应的文件html
.html 文件直接导入模板
,但是会有一个问题。如果另一个应用程序的模板文件与 index.html
冲突怎么办?那么django
将无法区分它们。 // 这里只展示主要的代码块,避免代码块过长
// todolist/template/todolist/index.html
<body>
<div class="flex justify-center mt-20">
<form action="/todo/add" method="post">
{% csrf_token %}
<div class="mb-3 xl:w-96 flex">
<input type="text" class="
form-control
block
w-full
px-2
py-1
text-sm
font-normal
text-gray-700
bg-white bg-clip-padding
border border-solid border-gray-300
rounded
transition
ease-in-out
mr-2
focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
" id="exampleFormControlInput4" placeholder="" name="title" /><button type="submit"
class="inline-block px-6 py-2.5 bg-blue-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out">add</button>
</div>
</form>
</div>
<div class="flex justify-center">
{% if error_message %}
<div>
<a href="#!"
class="text-red-600 hover:text-red-700 transition duration-300 ease-in-out mb-4">{{error_message}}</a>
</div>
{% endif %}
<ul class="bg-white rounded-lg border border-gray-200 w-96 text-gray-900">
{% for item in list %}
<li class="px-6 py-2 border-b border-gray-200 w-full rounded-t-lg relative"><span>{{ item.title }}</span>
<form action="/todo/delete" method="post">
{% csrf_token %}
<button type="submit" name='id' value={{item.id}}
class="px-6 py-1 border-2 border-red-600 text-red-600 font-medium text-xs leading-tight uppercase rounded hover:bg-black hover:bg-opacity-5 focus:outline-none focus:ring-0 transition duration-150 ease-in-out absolute inset-y-2 right-2">remove</button>
</form>
</li>
{% empty %}
<li class="px-6 py-2 border-b border-gray-200 w-full rounded-t-lg relative"><span>添加一条新待办吧!</span>
{% endfor %}
</ul>
</div>
<ul>
</ul>
</div>
// 引入tailwindcss
<script ></script>
// 这里只展示主要的代码块,避免代码块过长
复制代码
index.html
中显示数据的代码的一部分。这里使用模板语法来遍历list
,也就是上面创建的TodoList。 模型数据。
请求和views.py
(add
, , IndexView
)。IndexView
中,我们继承了通用视图 ListView
,它抽象地显示了对象列表(❙为通用视图,我们需要一个模型❙ 属性),默认根据ListView
自动定义默认模板/_list.html
。在这里,使用 template_name
,我们让它指向我们创建的模板index.html
。 context_object_name
属性指定模板中的变量名称,即上面模板中提到的变量list
。 get_queryset
方法来检索视图的项目列表(必须是可迭代对象)// todolist/views.py
from .models import TodoList
from django.views import generic
class IndexView(generic.ListView):
template_name = 'todolist/index.html'
context_object_name = 'list'
def get_queryset(self):
return TodoList.objects.all()
复制代码
request
对象是当前用户请求的信息的集合。我们收到了他当前的判决请求。如果不是POST,则不予处理。然后获取POSTtitle
属性,并使用将数据发送到数据库 (删除
的操作类似)
// todolist/views.py
from django.http import HttpResponseRedirect
from django.urls import reverse
def add(request):
if(request.method=='POST'):
val=request.POST.get('title')
if(not val):
return HttpResponseRedirect( reverse('todolist:index'), {
'error_message': "标题不能为空.",
})
p=TodoList.objects.create(title=val)
p.save()
return HttpResponseRedirect(reverse('todolist:index'))
复制代码
// todolist/views.py
def delete(request):
if(request.method=='POST'):
id=request.POST.get('id')
if(id is None):
return HttpResponseRedirect( reverse('todolist:index'), {
'error_message': "ID有误.",
})
TodoList.objects.get(id=id).delete()
return HttpResponseRedirect(reverse('todolist:index'))
复制代码
todolist
已经达到了原图的效果。您可以添加和修改数据库中的数据。然后你可以优化这个应用程序。比如可以在双击事件时改变事件的内容,添加一些动画效果等。 jdango
的简单使用。要继续学习,请前往Django
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。