request.user.attribute返回不需要的值

时间:2017-11-06 22:25:38

标签: django django-views

为什么以下打印(所有者)返回的值与我的模型中的内容不同?是否可以获得下面定义的formattedusername?我已经简化了我的def配置文件(请求)并取出了我的其他参数,直到我找到了获得formattedusername的解决方案。

def profile(request):
    owner = User.objects.get (formattedusername=request.user.formattedusername)
    args = {'user':request.user.formattedusername}
    print (owner)
    return render(request, 'accounts/profile.html', args)

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
@3-alphas4numeric
[06/Nov/2017 16:18:11] "GET /account/profile/ HTTP/1.1" 200 1416

我的模型中的formattedusername作为HCA \ 3-alphas4numeric存储在数据库中,它也由以下定义,它也是我所有其他模型中的关键字段,并且没有'因为它是一个预先存在的数据库,所以使用整数作为密钥:

class User(AbstractBaseUser, PermissionsMixin):



    email = models.EmailField(unique=True)
    username = models.CharField(max_length=7, unique=True)
    formattedusername = models.CharField(max_length=11, unique=True, primary_key = True)
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=140)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    facility = models.CharField(max_length=140)
    jobdescription = models.CharField(max_length=140)
    positiondescription = models.CharField(max_length=140)
    coid = models.CharField(max_length=5)
    streetaddress = models.CharField(max_length=140)



    USERNAME_FIELD = 'username'

    class Meta:
        app_label = 'accounts'
        db_table = "user"

    def save(self, *args, **kwargs):
        self.formattedusername = '{domain}\{username}'.format(
            domain='HCA', username=self.username)
        super(User, self).save(*args, **kwargs);

1 个答案:

答案 0 :(得分:1)

执行print(owner)后,您将打印出USERNAME_FIELD的值。这就是AbstractBaseUser.__str__的实施方式。

def get_username(self):
    "Return the identifying username for this User"
    return getattr(self, self.USERNAME_FIELD)

def __str__(self):
    return self.get_username()