Python/Django表单提交异常:点击编辑按钮无响应问题
Django任务管理表单编辑按钮无响应问题
问题现象
点击「Изменить(编辑)」按钮后页面无任何变化,无法进入任务修改状态。预期点击后应显示编辑输入框,支持修改保存和取消操作。
相关代码
urls.py
from django.urls import path from . import views app_name = 'todoist' urlpatterns = [ path('', views.index, name='index'), path('add', views.add, name='add'), path('delete/<int:today_id>/', views.delete, name='delete'), path('update/<int:today_id>/', views.update, name='update'), path('edit/<int:today_id>/', views.edit, name='edit'), ]
views.py
from django.shortcuts import render,redirect from .models import Today from django.views.decorators.http import require_http_methods def index(request): todos = Today.objects.all() return render(request, 'today.html', {'todos':todos}) @require_http_methods(['POST']) def add(request): tasks = request.POST["tasks"] task = Today(tasks=tasks) task.save() return redirect('todoist:index') def delete(request, today_id): todo = Today.objects.get(id=today_id) todo.delete() return redirect('todoist:index') def update(request, today_id): todo = Today.objects.get(id=today_id) todo.tasks = request.POST.get('tasks') todo.save() return redirect('todoist:index') def edit(request, today_id): todo = Today.objects.get(id=today_id) todo.edit_mode = True todo.save() return redirect('todoist:index')
today.html
<title>Todoist</title> <h1>Сегодня</h1> <h2>Задачи</h2> <form method="POST" action="{% url 'todoist:add' %}">{% csrf_token %} <input type="text" name='tasks' pattern=". {2,}" required title='Минимум два символа!!!'> <button type="submit" class="save btn btn-default">Добавить задачу</button> </form> <ol> {% for todo in todos %} <div> {% if todo.edit_mode %} <form action="{% url 'todoist:update' today_id=todo.id %}" method="POST"> {% csrf_token %} <input type="text" name="tasks" value="{{ todo.tasks }}"> <button type="submit" class="save btn btn-default">Сохранить</button> </form> <a href="{% url 'todoist:index' %}">Отмена</a> {% else %} <li><p>{{ todo.tasks }}</p></li> <a href="{% url 'todoist:delete' today_id=todo.id %}">Удалить</a> <a href="{% url 'todoist:edit' today_id=todo.id %}">Изменить</a> {% endif %} </div> {% endfor %} </ol>
浏览器渲染后的HTML
<title>Todoist</title> <h1>Сегодня</h1> <h2>Задачи</h2> <form method="POST" action="/add" ><input type="hidden" name="csr" value="igFpTSKXEVo2dBXw0LdfQT8PZSc78SCdC0rID6Ir3N2cDQOzUeNUdwtMdaTsU84R"> <input type="text" name='tasks' pattern=". {2,}" required title='Минимум два символа!!!'> <button type="submit" class="save btn btn-default">Добавить задачу</button> </form> <ol> <div> <li><p>паттат</p></li> <a href="/delete/118/">Удалить</a> <a href="/edit/118/">Изменить</a> </div> </ol>
问题分析
- CSRF令牌异常:渲染后的HTML中,CSRF令牌的name属性为
csr(正确应为csrfmiddlewaretoken),会导致Django的CSRF验证失败,拦截合法请求。 - 取消功能未重置编辑状态:当前取消按钮仅返回首页,未将任务的
edit_mode改回False,导致任务可能一直处于编辑状态。 - update视图未限制请求方法:update视图未添加POST请求限制,存在被GET请求误触发的风险。
- 模型字段验证:需确认Today模型是否正确定义了
edit_mode布尔字段,默认值为False。
修复步骤
1. 修正CSRF令牌渲染
检查模板中{% csrf_token %}的书写,确保无拼写错误,渲染后生成的隐藏输入框name属性应为csrfmiddlewaretoken。若为渲染异常,可手动添加CSRF字段:
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
2. 完善update视图
添加POST请求限制,并在保存后退出编辑模式:
@require_http_methods(['POST']) def update(request, today_id): todo = Today.objects.get(id=today_id) todo.tasks = request.POST.get('tasks') todo.edit_mode = False todo.save() return redirect('todoist:index')
3. 新增取消编辑视图
- 在urls.py中添加取消路由:
path('cancel/<int:today_id>/', views.cancel, name='cancel'),
- 在views.py中实现cancel函数:
def cancel(request, today_id): todo = Today.objects.get(id=today_id) todo.edit_mode = False todo.save() return redirect('todoist:index')
- 修改today.html中的取消链接:
<a href="{% url 'todoist:cancel' today_id=todo.id %}">Отмена</a>
4. 验证模型字段
确保Today模型包含edit_mode字段:
from django.db import models class Today(models.Model): tasks = models.CharField(max_length=200) edit_mode = models.BooleanField(default=False) def __str__(self): return self.tasks
若已存在此字段,需确保数据库已迁移:
python manage.py makemigrations python manage.py migrate
验证效果
- 重启Django服务器,访问任务列表页面。
- 点击「Изменить(编辑)」按钮,页面刷新后应显示该任务的编辑输入框、「Сохранить(保存)」和「Отмена(取消)」按钮。
- 修改任务内容后点击保存,任务更新并退出编辑模式。
- 点击取消按钮,任务退出编辑模式,回到正常显示状态。
内容的提问来源于stack exchange,提问作者Treeesk
相关产品推荐
相关产品推荐

