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

Django urls.py语法错误求助:PowerShell运行runserver报错

解决Django urls.py的语法错误问题

我来帮你揪出导致PowerShell报错的语法问题,你的urls.py里有几处小的语法疏漏,咱们一步步修正:

先看你代码里的错误点:

  • order_by("-date"[:25]):这里给排序字符串"-date"加切片操作完全没必要,逻辑上也不对——你是想按date字段倒序排列,直接写order_by("-date")就可以了。
  • template_name=("blog/blog.html"):这里的圆括号是多余的,直接用字符串赋值就行,写成template_name="blog/blog.html"。
  • 函数调用未闭合:你在template_name=("blog/blog.html")后面直接写了列表的闭合符],但ListView.as_view()和url()这两个函数的括号都没完整闭合,这是触发语法错误的核心原因。

修正后的完整代码:

from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post

urlpatterns = [
    url(
        r'^$', 
        ListView.as_view(
            queryset=Post.objects.all().order_by("-date"),
            template_name="blog/blog.html"
        )
    )
]

我把代码做了换行格式化,这样更易读,也能清楚看到每个函数的括号都正确闭合了。

现在再运行python manage.py runserver,应该就不会再出现语法错误啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:59:34