1

我认为这当然不是一个新问题,但它是这样的:

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

/发票/客户/97/

(客户发票#97)

这很好,但我需要合并一些身份验证,以便作为客户个人资料一部分的用户无法通过手动输入 /invoices/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")

必须是更好/更简单的方法来处理这个问题 - 有什么想法吗?

干杯

4

2 回答 2

2

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

这样,无论您的代码在哪里尝试为客户获取发票,如果当前状态无法访问发票,则始终会引发异常,并且您不必担心行为不一致,只要您使用这些方法。

于 2009-06-10T14:01:09.577 回答
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装饰器。

于 2009-06-10T19:45:35.310 回答