找不到Django slug链接编辑页面

时间:2016-12-22 18:12:52

标签: python django slug

当我使用slug作为我的网址时,我遇到了麻烦。它说没有帖子符合查询。

在编辑和删除页面中发生的麻烦,结果在详细页面中仍然可以正常工作。

但奇怪的是,post.views.post_detail引发了404错误,而不是post_update。

我在帖子应用中的网址

urlpatterns = [

url(r'r^$', post_list, name='list'),
url(r'^create/$', post_create, name='create'),
url(r'^(?P<slg>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slg>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<slg>[\w-]+)/delete/$', post_delete),

]

观点

def post_detail(request, slg=None):
    instance = get_object_or_404(Post, slg=slg)
    context = {
    "title":intance.title,
    "instance":instance
    }
    return render(request, "post_detail.html", context)

def post_update(request, slg=None):
    instance = get_object_or_404(Post, slg=slg)
    form = PostForm(request.POST or None, request.FILES or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "title":instance.title,
        "instance":instance,
        "form", form,
    }
    return render(request, "post_form.html", context)

get_absolute_url函数也已经返回了slg。 唯一的问题是在编辑页面中找不到帖子,即使标题标题与当前可用帖子匹配。

System check identified no issues (0 silenced).
December 23, 2016 - 17:52:00
Django version 1.9.7, using settings 'blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Not Found: /hahaha/edit/
[23/Dec/2016 17:52:08] "GET /hahaha/edit/ HTTP/1.1" 404 1725

就像post_update函数不会执行。

可能出现什么问题? 谢谢。

1 个答案:

答案 0 :(得分:2)

您在网址中缺少单引号'。网址格式应有效str

url(r'r^$', post_list, name='list'),
url(r'^create/$', post_create, name='create'),
#              ^
url(r'^(?P<slg>[\w-]+)/$', post_detail, name='detail'),
#                       ^
url(r'^(?P<slg>[\w-]+)/edit/$', post_edit, name='edit'), 
#                            ^
url(r'^(?P<slg>[\w-]+)/delete/$', post_delete),
#                              ^