python django todolist 增删改查

image.png

git:https://github.com/huangantai/todolist.git
1、
pip install django=='2.1'
django-admin startproject todolist
django-admin startapp simpletodo
pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
2、settings.py 和 urls.py 设置

settings.py (注释csrf中间件)

ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'simpletodo',
'xadmin',
'crispy_forms',
'reversion',
]
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')

urls.py

from django.urls import path,include
from simpletodo import views
import xadmin
xadmin.autodiscover()

from xadmin.plugins import xversion
xversion.register_models()

urlpatterns = [
path('admin/', xadmin.site.urls),
path(r'', views.todolist),
path(r'simpletodo/',include('simpletodo.urls'))
]

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py collectstatic

3、simpletodo/models.py adminx.py urls.py views.py

models.py

from django.db import models
from django.contrib.auth.models import User

Create your models here.

class Todo(models.Model):
id=models.AutoField(primary_key=True)
user = models.ForeignKey(User,on_delete=models.CASCADE)
todo = models.CharField(max_length=50)
flag = models.CharField(max_length=2)
priority = models.CharField(max_length=2)
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']

adminx.py

import xadmin
from simpletodo.models import Todo

Register your models here.

class TodoAdmin(object):
list_display = ['user', 'todo', 'priority', 'flag', 'pubtime']
list_filter = ['pubtime','priority']
ordering = ['-pubtime']
list_editable=['todo','priority','flag']

xadmin.site.register(Todo, TodoAdmin)
[root@centos8 simpletodo]# vi adminx.py
[root@centos8 simpletodo]# cat adminx.py
from xadmin import views
import xadmin

class BaseSetting(object):
"""xadmin的基本配置"""
enable_themes = True # 开启主题切换功能
use_bootswatch = True

class GlobalSettings(object):
"""xadmin的全局配置"""
site_title = "todolist" # 设置站点标题
site_footer = "-todolist-" # 设置站点的页脚
menu_style = "accordion" # 设置菜单折叠

xadmin.site.register(views.CommAdminView, GlobalSettings)
xadmin.site.register(views.BaseAdminView, BaseSetting)

from simpletodo.models import Todo

Register your models here.

class TodoAdmin(object):
list_display = ['user', 'todo', 'priority', 'flag', 'pubtime']
list_filter = ['pubtime','priority']
ordering = ['-pubtime']
list_editable=['todo','priority','flag']

xadmin.site.register(Todo, TodoAdmin)

urls.py

!/usr/bin/python

-- coding: utf-8 --

from django.contrib import admin
from django.urls import path,include
from simpletodo import views

urlpatterns = [
path(r'',views.todolist),
path(r'addtodo/', views.addtodo,name='add'),
path(r'todofinish/<int:id>', views.todofinish,name='finish'),
path(r'todobackout/<int:id>', views.todoback,name='backout'),
path(r'updatetodo/<int:id>', views.updatetodo,name='update'),
path(r'tododelete/<int:id>', views.tododelete,name='delete')
]

views.py

from django.shortcuts import render,render_to_response
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.http import Http404
from simpletodo.models import Todo

Create your views here.

def todolist(request):
todolist=Todo.objects.filter(flag="1")
finishtodos=Todo.objects.filter(flag="0")
return render_to_response('simpletodo.html',{'todolist':todolist,'finishtodos':finishtodos})

def todofinish(request,id=''):
todo=Todo.objects.get(id=id)
print(todo.flag,id)
if todo.flag=="1":
todo.flag="0"
todo.save()
return HttpResponseRedirect('/simpletodo/')

def todoback(request,id=''):
todo=Todo.objects.get(id=id)
if todo.flag=="0":
todo.flag="1"
todo.save()
return HttpResponseRedirect('/simpletodo/')

def tododelete(request,id=''):
try:
todo=Todo.objects.get(id=id)
except Exception:
raise Http404
if todo:
todo.delete()
return HttpResponseRedirect('/simpletodo/')

def addtodo(request):
if request.method=='POST':
atodo=request.POST['todo']
priority=request.POST['priority']
if not priority:priority=0
user = User.objects.get(id='1')
todo = Todo(user=user, todo=atodo, priority=priority, flag="1")
todo.save()
todolist = Todo.objects.filter(flag="1")
finishtodos = Todo.objects.filter(flag="0")
return render_to_response('showtodo.html',{'todolist': todolist, 'finishtodos': finishtodos})
else:
todolist = Todo.objects.filter(flag="1")
finishtodos = Todo.objects.filter(flag="0")
return render_to_response('simpletodo.html',{'todolist': todolist, 'finishtodos': finishtodos})

def updatetodo(request,id=''):
if request.method == 'POST':
atodo = request.POST['todo']
priority = request.POST['priority']
user = User.objects.get(id='1')
todo=Todo.objects.get(id=id)
todo.todo=atodo
todo.priority=priority
todo.save()
todolist = Todo.objects.filter(flag="1")
finishtodos = Todo.objects.filter(flag="0")
return render_to_response('simpletodo.html',{'todolist': todolist, 'finishtodos': finishtodos})
else:
try:
todo = Todo.objects.get(id=id)
except Exception:
raise Http404
return render_to_response('updatatodo.html', {'todo': todo})

4、templates/simpletodo.html updatatodo.html showtodo.html

simpletodo.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Simple Todo{% endblock %}</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<script src="/static/js/modernizr.js"></script>
<script src="/static/js/jquery.js"></script>
{% block extra_head %}
<style>
body {padding-top: 40px;}
.ftodo{text-decoration : line-through ; }
textarea{ width: 97%;
padding: 5px;
font-size: 14px;
resize: vertical;}
</style>
<script type="text/javascript">
function sendtwitter(){
('#myModal form').submit(function(){.ajax({
type: "POST",
data: ('#myModal form').serialize(), url: "{% url 'add' %}", cache: false, dataType: "html", success: function(html, textStatus) {('#todo').replaceWith(html);
('#myModal').modal('hide');('#myModal form')[0].reset();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.'); } }); return false; }); }(document).ready(function(){
sendtwitter();
})
</script>
{% endblock %}
</head>
<body>
<div class="container">
<div class="row">
<div class="span8 offset2">
<div id="todo" class="well">
{% block todo %}
<table class="table table-hover">
<thead>
<tr>
<td>
<h3 class="text-success"><a href='/simpletodo/'>待办事项</a></h3>
</td>
</tr>
</thead>
<tbody>
{% for todo in todolist %}
{% if todo.priority == '1' %}
<tr class='error'>
{% endif %}
{% if todo.priority == '2' %}
<tr class='warning'>
{% endif %}
{% if todo.priority == '3' %}
<tr class='info'>
{% endif %}
<td class="todo">{{ todo.todo }}</td>
<td class="todo">{{ todo.pubtime|date:'Y-m-d'}}</td>
<td class="te">
<div class="span2">
<a href="{% url 'finish' todo.id %}" title="finish"><i class=" icon-ok"></i></a>
<a href="{% url 'update' todo.id %}" title="edit"><i class="icon-edit"></i></a>
<a href="{% url 'delete' todo.id %}" title="delete"><i class="icon-trash"></i></a>
</div>
</td>
</tr>
{% endfor %}
{% for ftodo in finishtodos %}
<tr class='success'>
<td class="ftodo muted">{{ ftodo.todo }}</td>
<td class="ftodo muted">{{ ftodo.pubtime|date:'Y-m-d'}}</td>
<td class="te">
<div class="span2">
<a href="{% url 'backout' ftodo.id %}" title="redo"><i class=" icon-repeat"></i></a>
<a href="{% url 'update' ftodo.id %}" title="edit"><i class="icon-edit"></i></a>
<a href="{% url 'delete' ftodo.id %}" title="delete"><i class="icon-trash"></i></a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a class="btn btn-success" href="#myModal" role="button" data-toggle="modal">
<i class="icon-plus icon-white"></i><span > ADD</span>
</a>
{% endblock %}
</div>
</div>
</div>
</div>
<div class="modal hide fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Add TODO</h3>
</div>
<form action="" method="post">{% csrf_token %}
<div class="modal-body">
<textarea name="todo" class="txtodo" id="txtodo" required="required">{{ todo.todo }}</textarea>
<fieldset>
<label class="radio inline" for="priority">
<span class="label label-info">Priority</span>
</label>
<label class="radio inline" for="priority">
<input type="radio" name="priority" value="1"/>
<span class="label label-important">紧急</span>
</label>
<label class="radio inline" for="priority">
<input type="radio" name="priority" value="2"/>
<span class="label label-warning">重要</span>
</label>
<label class="radio inline" for="priority">
<input type="radio" name="priority" value="3"/>
<span class="label label-success">一般</span>
</label>
</fieldset>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id="send" class="btn btn-success" type="submit" name="submit" >Save changes</button>
</div>
</form>
</div>
<script src="/static/js/bootstrap.min.js"></script>
</body>
</html>

updatatodo.html

{% extends 'simpletodo.html'%}

{% block title %} update Todo {% endblock %}

{% block todo %}
<form action="{% url 'update' todo.id %}" method="post">{% csrf_token %}
<div class="modal-body">
<textarea name="todo" class="txtodo" id="txtodo" required="required">{{ todo.todo }}</textarea>
<fieldset>
<label class="radio inline" for="priority">
<span class="label label-info">Priority</span>
</label>
<label class="radio inline" for="priority">
<input type="radio" name="priority" value="1" {% if todo.priority == '1' %} checked{% endif %}/>
<span class="label label-important">紧急</span>
</label>
<label class="radio inline" for="priority">
<input type="radio" name="priority" value="2" {% if todo.priority == '2' %} checked{% endif %}/>
<span class="label label-warning">重要</span>
</label>
<label class="radio inline" for="priority">
<input type="radio" name="priority" value="3" {% if todo.priority == '3' %} checked{% endif %}/>
<span class="label label-success">一般</span>
</label>
</fieldset>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id="send" class="btn btn-success" type="submit" name="submit" >Save changes</button>
</div>
</form>
{% endblock %}

showtodo.html

<div id="todo" class="well">
{% block todo %}
<table class="table table-hover">
<thead>
<tr>
<td>
<h3 class="text-success">待办事项</h3>
</td>
</tr>
</thead>
<tbody>
{% for todo in todolist %}
{% if todo.priority == '1' %}
<tr class='error'>
{% endif %}
{% if todo.priority == '2' %}
<tr class='warning'>
{% endif %}
{% if todo.priority == '3' %}
<tr class='info'>
{% endif %}
<td class="todo">{{ todo.todo }}</td>
<td class="te">
<div class="span2">
<a href="{% url 'finish' todo.id %}" title="finish"><i class=" icon-ok"></i></a>
<a href="{% url 'update' todo.id %}" title="edit"><i class="icon-edit"></i></a>
<a href="{% url 'delete' todo.id %}" title="delete"><i class="icon-trash"></i></a>
</div>
</td>
</tr>
{% endfor %}
{% for ftodo in finishtodos %}
<tr class='success'>
<td class="ftodo muted">{{ ftodo.todo }}</td>
<td class="te">
<div class="span2">
<a href="{% url 'backout' ftodo.id %}" title="finish"><i class=" icon-repeat"></i></a>
<a href="{% url 'update' ftodo.id %}" title="edit"><i class="icon-edit"></i></a>
<a href="{% url 'delete' ftodo.id %}" title="delete"><i class="icon-trash"></i></a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a class="btn btn-success" href="#myModal" role="button" data-toggle="modal">
<i class="icon-plus icon-white"></i><span > ADD</span>
</a>
{% endblock %}
</div>
5、static/css js img

css

bootstrap.min.css

img

glyphicons-halflings.png glyphicons-halflings-white.png

js

ajaxpost.js bootstrap.js bootstrap.min.js jquery.js modernizr.js
(document).ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)/.test(method));
}

if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}

});

6、修改settings.py

STATIC_ROOT = os.path.join(BASE_DIR, '/static')

STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),]
7、
python manage.py makemigrations
python manage.py migrate
python runserver 0.0.0.0:9999 &

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341

推荐阅读更多精彩内容

  • 模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。软件设计中通常用耦合度和内聚...
    riverstation阅读 2,057评论 0 8
  • 去年的事情特别多,也没有什么时间充电学习。今年目测轻松一点,年初本来计划就好好休息一下,结果一晃2017就度过了一...
    灰豹儿阅读 618评论 0 2
  • 已经同步到gitbook,想阅读的请转到gitbook: Django 1.10 中文文档 This tutori...
    leyu阅读 2,658评论 3 13
  • Django 准备 “虚拟环境为什么需要虚拟环境:到目前位置,我们所有的第三方包安装都是直接通过 pip inst...
    33jubi阅读 1,313评论 0 5
  • 情绪真是难驾驭的家伙。 今早起床精神不错,发现昨晚能九点钟就犯困是件值得庆幸的事。 来到学校也算...
    jackhot阅读 248评论 0 0