gpt4 book ai didi

python - Django,网址不匹配

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:59 26 4
gpt4 key购买 nike

这可能是一个重复的问题,但我在这里找不到任何答案。我正在尝试编写一种能够采用两种不同模型的方法。我有一个 Post 模型和一个 Comment 模型,我希望 vote_up 方法来处理对这两个模型的投票。

View .py

def vote_up(request, obj): #portotype not working atm...
if isinstance(obj, Post):
o = Post.objects.get(id=obj.id)
elif isinstance(obj, Comment):
o = Comment.objects.get(id=obj.id)
else:
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) #add 'something went wrong' message
o.votes += 1
o.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

网址.py

urlpatterns = patterns('',
url(r'^vote_up/(?P<obj>\d+)/$', 'post.views.vote_up'),
url(r'^post_vote_down/(?P<post_id>\d+)/$', 'post.views.post_vote_down'), # works fine no instance check here, using separate methods for Post/Comment
url(r'^comment_vote_down/(?P<comment_id>\d+)/$', 'post.views.comment_vote_down'),
)

我得到的错误是列出我现有的 url 和:当前的 URL,post/vote_up/Post 对象,与其中任何一个都不匹配。或者当前的 URL post/vote_up/Comment 对象与其中任何一个都不匹配。

我猜\d+ 是坏人,但似乎找不到正确的语法。

最佳答案

正如 Burhan 所说,您不能在 URL 中发送对象,只能发送 key 。但另一种方法是将模型包含在 URLconf 本身中:您可以使用单个模式,但也可以在那里捕获模型名称。

url(r'^(?P<model>post|comment)_vote_down/(?P<pk>\d+)/$', 'post.views.post_vote_down'),

)

然后在 View 中:

def vote_up(request, model, pk):
model_dict = {'post': Post, 'comment': Comment}
model_class = model_dict[model]
o = model_class.objects.get(pk=pk)

关于python - Django,网址不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18715725/

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