gpt4 book ai didi

python - 我如何在 django 重定向中使用 kwargs,我有一个错误

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:25 25 4
gpt4 key购买 nike

我想为我的详细信息页面创建一个带有 kwargs 的重定向 Django 。我有一个评论系统,我想重定向到用户所在的页面。

我的网址:

from django.urls import path, re_path
from .views import blog, detail, posts_by_tag

app_name = "blog"
urlpatterns = [
re_path('^$',blog, name="blog"),
re_path('^(?P<year>[\d+]{1,4})/(?P<month>[\d+]{1,2})/(?P<day>[\d+]
{1,2})/(?P<slug>[\w-]+)/$', detail, name= "detail"),
re_path('^(?P<tag>[\w-]+)/$',posts_by_tag, name="tag"),
]

我的详细信息:

def detail(request, slug, year, month, day):
post = get_object_or_404(Post,slug=slug,
created__year = year,
created__month = month,
created__day = day)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == "POST":
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post

new_comment.save()
return redirect('blog:detail', kwargs=
{'slug':slug,'created__year':year,'created__month' : month,
'created__day' : day,})
else:
comment_form = CommentForm()
context = {
'post':post,
'comments':comments,
'new_comment':new_comment,
'comment_form':comment_form,
}
return render(request, 'blog/detail.html', context)

我的错误是:

Reverse for 'detail' with keyword arguments '{'slug': 'django-python',
'created__year': '2019', 'created__month': '7', 'created__day': '1'}' not found.
1 pattern(s) tried:
['blog/(?P<year>[\\d+]{1,4})/(?P<month>[\\d+]{1,2})/(?P<day>[\\d+]{1,2})/(?P<slug>[\\w-]+)/$']

最佳答案

文档在 examples section 中显示了这一点:

2) By passing the name of a view and optionally some positional or keyword arguments; the URL will be reverse resolved using the reverse() method:

def my_view(request):
...
return redirect('some-view-name', foo='bar')

你试过这个吗?

return redirect('blog:detail', slug=slug, year=year, month=month, day=day)

关于python - 我如何在 django 重定向中使用 kwargs,我有一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56840884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com