2009-06-10 76 views
0

当然不是一个新问题,我想访问,但这里有云:限制页面浏览到特定的用户/客户

在我的Django的基于订购系统中的每个用户(谁不是人员)相关的CustomerProfile对象,将该用户与正确的Customer对象进行匹配。该客户用户可以登录并查看未完成的发票。要查看客户的发票,您导航到这样的事情:

/发票/客户/ 97/

(客户发票#97)

这很好,但我需要加入一些身份验证,以便用户谁是客户个人资料的一部分,例如(发票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

一个字段添加到您的发票模式叫用户:

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

然后检索记录这样一个特定的用户:

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

检索发票给定用户随后与反向琐碎关系:

request.user.invoices.all() 

而且,看@login_required装饰。

2

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

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

相关问题