You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django商品编辑失效:Reverse for 'edit'未找到问题求助

解决Django中"Reverse for 'edit' not found"错误(无forms.py编辑场景)

出现这个错误的核心原因有两个:一是URL路由未正确配置edit视图的命名规则,二是模板调用URL时没有传递视图要求的id参数。下面分步骤解决:

1. 检查并配置URL路由

首先确保你的blog应用路由(blog/urls.py)正确设置了命名空间和edit路由:

from django.urls import path
from . import views

app_name = 'blog'  # 必须设置命名空间,和模板中的`blog:edit`对应

urlpatterns = [
    # 其他路由(比如列表、详情页)...
    path('edit/<int:id>/', views.edit, name='edit'),  # 这里的name='edit'是关键,同时要包含id参数
]

还要确认项目根路由(urls.py)已经包含blog的路由:

from django.urls import include, path

urlpatterns = [
    # 其他项目路由...
    path('blog/', include('blog.urls')),
]

2. 修正模板中的表单Action

你的视图edit需要接收id参数来定位要编辑的商品,模板里必须传递这个参数,同时因为涉及文件上传,要添加enctype="multipart/form-data"属性:

{% for el in posts %}
<form action="{% url 'blog:edit' el.id %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" placeholder="Название" name="title" value="{{ el.title }}"><br>
    <textarea placeholder="Текст статьи" rows="8" cols="80" name="text">{{ el.text }}</textarea><br>
    <input type="file" name="image"><br>
    <button type="submit">Сохранить изменения</button>
</form>
{% endfor %}

另外注意把textarea的默认值设为{{ el.text }},这样编辑时能显示原有内容。

3. 优化视图逻辑

原视图用title作为update_or_create的条件不合理,应该通过传入的id获取要编辑的对象,同时文件上传要使用request.FILES而非request.POST:

def edit(request, id):
    # 获取要编辑的对象,不存在则返回404
    try:
        obj = Posts.objects.get(id=id)
    except Posts.DoesNotExist:
        from django.http import Http404
        raise Http404("Статья не найдена")
    
    if request.method == 'POST':
        # 更新字段
        obj.title = request.POST.get("title")
        obj.text = request.POST.get("text")
        # 如果date是自动生成的时间戳,建议不要手动修改;如果需要编辑,要处理日期格式
        # obj.date = request.POST.get("date")
        # 处理图片上传
        if 'image' in request.FILES:
            obj.image = request.FILES['image']
        obj.save()
        # 保存后重定向到详情页或列表页,避免重复提交
        from django.shortcuts import redirect
        return redirect('blog:post_detail', id=id)  # 替换为你的实际视图名称
    
    # GET请求时,把对象传给模板
    return render(request, 'edit.html', {'post': obj})

内容的提问来源于stack exchange,提问作者Канистра Канистрова

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:30:56