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 &

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

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

友情链接更多精彩内容