0

我有这样的 User、UserClient 和 Client 模型:

一个客户端可以有多个用户:

  class Client(models.Model):

    user = models.OneToOneField(User)

    # Which company the client represents
    company = models.CharField(max_length=200, null=True)

    # Address of the company
    address = models.CharField(max_length=200, null=True)

    company_size = models.ForeignKey(CompanySize, null=True)

    account_type = models.ForeignKey(AccountType)

    billing_address = models.CharField(max_length=254, null=True)

    # Billing Information of the client

    def __unicode__(self):
        return self.user.username

class ClientUser(models.Model):

    user = models.OneToOneField(User)
    client = models.ForeignKey(Client)

    def __unicode__(self):
        return self.user.email

现在在模板中,我想这样做:

{% if user.is_client %}

{{ do_this }}

这该怎么做?

4

1 回答 1

1

假设模板中的“用户”是一个实例,添加方法django.contrib.auth.User的最简单解决方案是 monkeypatch :is_client()UserUser

# youmodels.py
from django.contrib.auth.models import User

# your models here...

def user_is_client(user):
    try:
        client = user.client
    except Client.DoesNotExist:
        return False
    else:
        return True

User.is_client = user_is_client

但正如 schneck 评论的那样,如果您的 django 版本足够新,那么拥有一个自定义用户模型可能会更好。

于 2013-10-01T09:05:50.827 回答