限制对特定用户/客户的页面查看访问权限

时间:2009-06-10 13:52:14

标签: django django-urls

我认为当然不是一个新问题,但在这里:

在我的基于Django的Order系统中,每个用户(不是员工)都与CustomerProfile对象相关,该对象将该用户与正确的Customer对象相匹配。该客户用户可以登录并查看未结清的发票。要查看客户的发票,请导航到以下内容:

/发票/客户/ 97 /

(客户发票#97)

哪个好,但我需要加入一些身份验证,以便属于客户个人资料的用户无法通过手动输入/发票/ customer / 92 /来查看其他客户的发票(例如发票92属于另一个客户)

我有这个,但它真的不是很好的代码(并且不起作用):

def customer_invoice_detail(request, object_id):
    user = threadlocals.get_current_user()
    try:
        userprofile = UserProfile.objects.get(user=user)
        user_customer = userprofile.customer.id
    except UserProfile.DoesNotExist:
        user_customer = None
    if (request.user.is_authenticated() and user_customer is not null) or request.user.is_staff():
        invoice = CustomerInvoice.objects.get(pk=object_id)
        product_list = CustomerInvoiceOrder.objects.filter(invoice=object_id)
        context = {
        'object': invoice,
        'product_list': product_list,
        }
        return render_to_response("invoices/customer_invoice_detail.html", context, context_instance=RequestContext(request))
    else:
        return HttpResponse("You are not authorised to view this invoice")

必须是一个更好/更简单的方法来处理这个 - 任何想法?

干杯

2 个答案:

答案 0 :(得分:2)

我建议为您的客户模型制作一些业务逻辑。这样您就可以使用get_invoices()方法返回该客户的发票清单。反过来,此方法将调用is_authenticated()方法,以确保当前状态允许检索受保护的客户数据,或引发异常。

有了这个,无论您的代码在哪里尝试为客户获取发票,如果当前状态无法访问发票,则始终会抛出异常,并且您不必担心长时间的不一致行为当你使用这些方法时。

答案 1 :(得分:2)

在您的发票模型中添加一个名为user的字段:

user = models.ForeignKey(User, related_name="invoices")

然后检索特定用户的记录,如下所示:

invoice = CustomerInvoice.objects.get(pk=object_id, user=request.user)

使用反向关系检索给定用户的发票是微不足道的:

request.user.invoices.all()

另外,请查看@login_required装饰器。

相关问题