Python 框架 Django快速入门 Todo案例

Django是什么

Django

初体验Django

DjangoTodoListDjangoPython

image-20220417204347333

创建一个新的项目

djangoDjango
django-admin startproject mysite

启动项目

mysite8000
python manage.py runserver

创建TodoList应用

这里的应用可以理解功能划分,而上面创建的项目是多个功能的网站。

python manage.py startapp todolist
mysite/settings.pyINSTALLED_APPStodolist.apps.TodolistConfigdjangotodolist
# Application definition

INSTALLED_APPS = [
    'todolist.apps.TodolistConfig',
    // ... other code
]

创建数据库

djangodb.sqlite3

如果你想使用其他数据库,你需要安装对应数据库的驱动,并在项目配置文件中的DATABASES中修改它

todolistmodelsTodoList

每个class代表一个模型,而下面的类变量则是模型的每个字段

// 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
djangodb.sqlite3

image-20220417212404879

创建路由

todolisturls.pydjangourl
// 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/adddelete
views.py

在项目中引用应用中的路由信息,其实我们也可以将路径直接写在该文件下的,但随着你的应用越来越多时该文件会越来越大,而且不好管理。

// mysite/urls.py
from django.contrib import admin
from django.urls import path,include

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

创建视图&模板

index.htmltodolist/template/todolist/index.html
djangotemplatehtmlindex.htmltemplateindex.htmldjango
// 这里只展示主要的代码块,避免代码块过长
// 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 src="https://cdn.tailwindcss.com"></script>

// 这里只展示主要的代码块,避免代码块过长
index.htmllistTodoList
views.pyurls.pyadddeleteIndexView
IndexViewListViewmodelListView/_list.htmltemplate_nameindex.html
context_object_namelist
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()

下面这两个方法是分别是对数据库的数据进行增、删的操作。

requestPOSTtitleTodoListdelete
// 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
jdangoDjango

image-20220417204347333