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 &

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末现使,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子旷痕,更是在濱河造成了極大的恐慌碳锈,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件欺抗,死亡現(xiàn)場離奇詭異售碳,居然都是意外死亡,警方通過查閱死者的電腦和手機绞呈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門贸人,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人报强,你說我怎么就攤上這事灸姊。” “怎么了秉溉?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵力惯,是天一觀的道長碗誉。 經(jīng)常有香客問我,道長父晶,這世上最難降的妖魔是什么哮缺? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮甲喝,結果婚禮上尝苇,老公的妹妹穿的比我還像新娘。我一直安慰自己埠胖,他們只是感情好糠溜,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著直撤,像睡著了一般非竿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上谋竖,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天红柱,我揣著相機與錄音,去河邊找鬼蓖乘。 笑死锤悄,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的嘉抒。 我是一名探鬼主播零聚,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼众眨!你這毒婦竟也來了握牧?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤娩梨,失蹤者是張志新(化名)和其女友劉穎沿腰,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體狈定,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡颂龙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了纽什。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片措嵌。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖芦缰,靈堂內(nèi)的尸體忽然破棺而出企巢,到底是詐尸還是另有隱情,我是刑警寧澤让蕾,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布浪规,位于F島的核電站或听,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏笋婿。R本人自食惡果不足惜誉裆,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望缸濒。 院中可真熱鬧足丢,春花似錦、人聲如沸庇配。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽讨永。三九已至滔驶,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間卿闹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工萝快, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留锻霎,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓揪漩,卻偏偏與公主長得像旋恼,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子奄容,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 模塊間聯(lián)系越多冰更,其耦合性越強,同時表明其獨立性越差( 降低耦合性昂勒,可以提高其獨立性)蜀细。軟件設計中通常用耦合度和內(nèi)聚...
    riverstation閱讀 2,070評論 0 8
  • 去年的事情特別多,也沒有什么時間充電學習戈盈。今年目測輕松一點奠衔,年初本來計劃就好好休息一下,結果一晃2017就度過了一...
    灰豹兒閱讀 629評論 0 2
  • 已經(jīng)同步到gitbook塘娶,想閱讀的請轉(zhuǎn)到gitbook: Django 1.10 中文文檔 This tutori...
    leyu閱讀 2,687評論 3 13
  • Django 準備 “虛擬環(huán)境為什么需要虛擬環(huán)境:到目前位置归斤,我們所有的第三方包安裝都是直接通過 pip inst...
    33jubi閱讀 1,324評論 0 5
  • 情緒真是難駕馭的家伙脏里。 今早起床精神不錯,發(fā)現(xiàn)昨晚能九點鐘就犯困是件值得慶幸的事虹曙。 來到學校也算...
    jackhot閱讀 251評論 0 0