Django,网址不匹配

时间:2013-09-10 09:52:01

标签: python django

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

views.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'))

urls.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,post / vote_up / Post对象与其中任何一个都不匹配。 要么 当前URL,post / vote_up / Comment对象与其中任何一个都不匹配。

我猜是\ d +是恶棍,但似乎无法找到正确的语法。

4 个答案:

答案 0 :(得分:4)

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

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

然后在视图中:

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

答案 1 :(得分:0)

改变这个:

 url(r'^vote_up/(?P<obj>\d+)/$', 'post.views.vote_up'),

url(r'^vote_up/(?P<obj>[-\w]+)/$', 'post.views.vote_up'),

\d+表示只有整数。

答案 2 :(得分:0)

您无法在URL中发送对象,您需要发送主键,然后从数据库中检索相应的对象。

def vote_up(request, obj): #portotype not working atm...
    try:
        o = Post.objects.get(pk=obj)
    except Post.DoesNotExist:
        o = Comment.objects.get(pk=obj)
        except Comment.DoesNotExist:           
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    o.votes += 1    
    o.save()    
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

答案 3 :(得分:0)

您需要在网址中区分评论和帖子:

urls.py

url(r'^vote_up/(?P<object_name>\w+)/(?P<id>\d+)/$', 'post.views.vote_up'),

views.py

def vote_up(request, object_name, id):
    if object_name == 'comment':
        # get id for comment
    if object_name == 'post':
        # get id for post
    else:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
相关问题