Django创建todolist应用

本案例使用Django框架创建了一个todolist应用。
Django创建todolist应用_第1张图片
Django创建todolist应用_第2张图片

文章目录

  • 虚拟环境使用
  • 创建project和app的相关步骤
    • 修改HelloWorld/settings.py
    • 修改HelloWorld/urls.py
  • todolist搭建
    • Model层
    • View层
  • 路由设置
  • 前端页面
  • 参考资料

虚拟环境使用

  1. 使用virtualenv
#创建虚拟环境
virtualenv venv

#cd到虚拟环境目录
#激活虚拟环境
source ./bin/activate

#退出虚拟环境
deactivate

#删除虚拟环境
rmvirtualenv venv
  1. 使用virtualenvwrapper
#创建虚拟环境
mkvirtualenv venv

#列出所有虚拟环境
lsvirtualenv

#激活虚拟环境
workon venv

#退出虚拟环境
deactivate

#停止虚拟环境所有软件包
rmvirtualenv venv

#可以使用pip list 查看已安装的包

#进入虚拟环境目录
cdvirtualenv

#进入虚拟环境site-packages
cdsitepackages

#列出目录下所有软件包
lssitepackages

创建project和app的相关步骤

#创建project
django-admin startproject HelloWorld

#创建app
python manage.py startapp SimpleTodo

修改HelloWorld/settings.py

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'SimpleTodo', 
]

#配置mysql数据库
DATABASES = {
  ...
}

修改HelloWorld/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import *
from . import view
urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'todolist',include('SimpleTodo.urls')),
]

todolist搭建

Model层

  1. 修改SimpleTodo/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Todo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    todo = models.CharField(max_length=50)
    flag = models.CharField(max_length=2, default='1')
    priority = models.CharField(max_length=2, default='0')
    pubtime = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return u'%d %s %s'%(self.id, self.todo, self.flag)

    class Meta: 
        ordering = ['priority', 'pubtime']
  1. 数据库迁移,命令行操作
#生成迁移文件
python manage.py makemigrations

#迁移数据库
python manage.py migrate

View层

  1. 修改SimpleTodo/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.models import User
from django.http import Http404
from SimpleTodo.models import Todo
# Create your views here.

# 获取todo列表
def todolist(request):
    todolist = Todo.objects.filter(flag=1)
    finishtodos = Todo.objects.filter(flag=0)
    return render(request, 'simpleTodo.html',
                  {'todolist': todolist, 'finishtodos': finishtodos},)

# 完成todo
def todofinish(request):
    id = request.GET.get('id','')
    if id == '':
        return HttpResponseRedirect('/todolist')

    todo = Todo.objects.get(id=id)
    if todo.flag == '1':
        todo.flag = '0'
        todo.save()
    return HttpResponseRedirect('/todolist')
    # todolist = Todo.objects.filter(flag=1)
    # return render(request, 'simpleTodo.html', {'todolist': todolist})

# 更改todo状态
def todoback(request):
    
    id = request.GET.get('id','')
    if id == '':
        return HttpResponseRedirect('/todolist')

    todo = Todo.objects.get(id=id)
    if todo.flag == '0':
        todo.flag = '1'
        todo.save()
    return HttpResponseRedirect('/todolist')

# 添加todo
def todoadd(request):
    if request.method == 'POST':
        todoc = request.POST['todo']
        priority = request.POST['priority']
        user = User.objects.get(id='1')
        todo = Todo(user=user, todo=todoc, priority=priority, flag='1')
        todo.save()
        todolist = Todo.objects.filter(flag=1)
        finishtodos = Todo.objects.filter(flag=0)
        return render(request, 'simpleTodo.html',
                      {'todolist': todolist, 'finishtodos': finishtodos},)
    else:
        todolist = Todo.objects.filter(flag=1)
        finishtodos = Todo.objects.filter(flag=0)
        return render(request, 'simpleTodo.html',
                      {'todolist': todolist, 'finishtodos': finishtodos},)

# 删除todo
def tododelete(request):
    id = request.GET.get('id','')
    if id == '':
        return HttpResponseRedirect('/todolist')

    try:
        todo = Todo.objects.get(id=id)
    except Exception:
        raise Http404
    if todo:
        todo.delete()
        return HttpResponseRedirect('/todolist')
    todolist = Todo.objects.filter(flag=1)
    return render(request, 'simpleTodo.html', {'todolist': todolist})
    

路由设置

  1. 修改SimpleTodo/urls.py
from django.urls import path,  include
from . import views
from django.conf.urls import url

urlpatterns = [
    path(r'', views.todolist, name='todolist'),
    url(r'/add', views.todoadd, name='todoadd'),
    url(r'/todofinish/', views.todofinish, name='finish'),
    url(r'/tododelete/', views.tododelete, name='delete'),
    url(r'/todoback/', views.todoback, name='back'),
]

前端页面

使用Bootstrap,具体参考官方文档

  1. 创建模板,设置templates/base.html
...
{% block mainbody %}

original

{% endblock %} ...
  1. 设置templates/simpleTodo.html
{% extends 'base.html' %}

{% block mainbody %}

To do Add

{% for todo in todolist %}
{{todo.pubtime}}

{{todo.todo}}

Finish Delete

{% endfor %}

Finished

{% for todo in finishtodos %}
{{todo.pubtime}}

{{todo.todo}}

Recover Delete

{% endfor %}
{% endblock %}

参考资料

  1. https://blog.csdn.net/hcx25909/article/details/24251427?utm_source=app

  2. 菜鸟教程

你可能感兴趣的:(python,django)