帮我用Django2.2写一个任务管理系统
时间: 2024-09-26 07:09:22 浏览: 36
Django的资产管理系统源码
创建一个任务管理系统,我们可以使用Django框架的模型、视图和模板来构建基本功能。以下是简化的步骤和关键代码示例,假设我们将任务分为待办任务和已完成任务两个状态。
1. **安装Django和相关库**:
```
pip install django
```
2. **设置项目和应用**:
创建一个新的Django项目和名为'task_manager'的应用:
```
django-admin startproject task_manager
cd task_manager
python manage.py startapp tasks
```
3. **models.py (tasks应用)**:
```python
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
status = models.CharField(choices=[('todo', '待办'), ('done', '完成')], default='todo')
assigned_to = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class TaskHistory(models.Model):
task = models.ForeignKey(Task, on_delete=models.CASCADE)
status = models.CharField(choices=[('todo', '待办'), ('done', '完成')])
changed_at = models.DateTimeField(auto_now_add=True)
```
4. **views.py (tasks应用)**:
```python
from django.shortcuts import render, get_object_or_404
from .models import Task, TaskHistory
def task_list(request):
tasks = Task.objects.all().order_by('-created_at')
return render(request, 'tasks/task_list.html', {'tasks': tasks})
def add_task(request):
if request.method == 'POST':
new_task = Task(title=request.POST['title'], description=request.POST['description'],
assigned_to=request.user)
new_task.save()
return redirect('task_list')
else:
return render(request, 'tasks/add_task.html')
def update_status(request, pk):
task = get_object_or_404(Task, pk=pk)
history_entry = TaskHistory(task=task, status=task.status)
history_entry.save()
task.status = request.POST['status']
task.save()
return redirect('task_list')
```
5. **urls.py (tasks应用) 和 main urls.py (task_manager项目)**:
```python
# tasks/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.task_list, name='task_list'),
path('add/', views.add_task, name='add_task'),
path('<int:pk>/update/<str:status>/', views.update_status, name='update_status'),
]
# main project's urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('tasks/', include('tasks.urls')),
]
```
6. **templates (tasks应用) - 添加HTML文件如task_list.html, add_task.html等**:
创建对应的模板文件,展示任务列表、添加任务表单和更新任务状态的界面。
7. **运行服务器**:
```
python manage.py runserver
```
现在你可以访问`http://localhost:8000/tasks/`查看任务管理系统的初步功能。记得根据实际需求调整和完善细节,比如权限控制、分页显示等。
阅读全文