Django Guardian权限错误:参数pk未传递给视图函数

时间:2015-10-29 04:53:27

标签: python django permissions django-views django-guardian

我有一个名为Message的模型,我使用django-guardian进行对象级权限。我们的想法是,消息实例中的from_userto_user都应具有can_view_message权限。此功能用于显示具有相同消息thread_id的消息列表(在创建消息时自动创建)。

@permission_required_or_403('can_view_message', (Message, 'pk', 'pk'))
def message_thread(request, pk):
    selected_message = Message.objects.get(pk=pk)
    threads = Message.objects.filter(thread_id=selected_message.thread_id)

    context = RequestContext(request, {
        'latest_messages': threads,
    })
    return render(request, 'myapp/messages_thread.html', context)

此请求的网址格式: url(r'^messages/([-_a-z0-9]{1,32})/$', message_views.message_thread),

这是消息模型:

class Message(models.Model):
    from_user = models.ForeignKey(User, verbose_name='From', related_name='%(class)s_from_user')
    to_user = models.ForeignKey(User, verbose_name='To', related_name='%(class)s_to_user')
    send_time = models.DateTimeField('Send Time', blank=True)
    msg_content = models.TextField('Message')
    thread_id = models.CharField('Thread', max_length=50, blank=True)

    class Meta:
        permissions = (
            ('can_view_message', 'Can View Message'),
        )

我使用post_create信号来分配权限:

def view_message(sender, instance, **kwargs):
    assign_perm('can_view_message', instance.from_user, instance)
    assign_perm('can_view_message', instance.to_user, instance)

post_save.connect(view_message, sender=Message, dispatch_uid="view_message_permission")

但是我收到以下错误但不知道原因:

GuardianError at /myapp/messages/13/
Argument pk was not passed into view function
Request Method: GET
Request URL:    http://127.0.0.1:8000/myapp/messages/13/
Django Version: 1.8.4
Exception Type: GuardianError
Exception Value:    
Argument pk was not passed into view function
Exception Location: /Library/Python/2.7/site-packages/guardian/decorators.py in _wrapped_view, line 111
Python Executable:  /usr/bin/python
Python Version: 2.7.6

非常感谢任何帮助,非常感谢你!

1 个答案:

答案 0 :(得分:0)

根据@Burhan Khalid的评论,我检查了我的请求网址,它是url(r'^messages/([-_a-z0-9]{1,32})/$', message_views.message_thread),

我在请求中使用pk将其更改为url(r'^messages/(?P<pk>[-\w]+)/$', message_views.message_thread),现在它完美无缺。