You need to enable JavaScript to run this app. Django触发TemplateSyntaxError:无法解析url标签中update_homepage的剩余内容
优惠活动
大模型
产品
解决方案
定价
更多

Django触发TemplateSyntaxError:无法解析url标签中update_homepage的剩余内容

修复方案

触发的原始报错:

TemplateSyntaxError at /
Could not parse the remainder: ' 'update_homepage'' from 'url 'update_homepage''

这个报错的直接原因是模板中的路由生成标签语法错误:Django的url是模板标签,必须用{% %}包裹,不能用变量输出的双大括号{{ }},模板引擎解析带空格的无效变量名时就会抛出对应的语法错误。
同时你的update_homepage路由要求传入pk路径参数,当前链接没有携带参数,即使语法修正也无法匹配路由。

逐文件修正代码

1. homepage.html 修正

原错误链接写法:

<a href="{{ url 'update_homepage'}}">Update</a>

修正后需要在每篇文章的循环内生成带文章id的更新链接,移除无意义的表单外{% csrf_token %}代码:

<h1>My Blog</h1>
{% for article in articles %}
    <div class="article">
        <h1>{{ article.title }}</h1>
        <h3>{{ article.text }}</h3>
        <a href="{% url 'update_homepage' article.pk %}">Update</a>
    </div>
{% endfor %}

2. views.py 修正

你写的两个视图都存在逻辑顺序问题:return语句放在POST请求处理代码之前,导致后续POST逻辑永远无法执行;同时存在未定义变量task的引用、未实例化表单的问题。
修正后的完整视图代码:

def index(request):
    articles = Article.objects.all()
    context = {'articles': articles}
    return render(request, 'able/homepage.html', context)


def updateHomepage(request, pk):
    # 先查询待更新的文章对象
    article = Editor.objects.get(id=pk)
    if request.method == 'POST':
        form = EditorForm(request.POST, instance=article)
        if form.is_valid():
            form.save()
            return redirect('/')
    # GET请求返回带已有数据的表单
    form = EditorForm(instance=article)
    context = {'form': form}
    return render(request, 'able/update_homepage.html', context)


def editorview(request):
    if request.method == 'POST':
        form = EditorForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    # GET请求实例化空表单返回页面
    context = {'editor': EditorForm()}
    return render(request, 'able/editor.html', context)

3. urls.py 配置

现有路由配置无语法错误,保持原样即可:

urlpatterns = [
    path('', views.index, name='homepage'),
    path('editor/', views.editorview),
    path('update_homepage/<str:pk>/', views.updateHomepage, name='update_homepage')
]

内容的提问来源于stack exchange,提问作者Agarb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 07:15:11