简体   繁体   English

从 model django 获取用户的用户名

[英]Grab username of User from model django

Not really sure if there is a duplicate question, probably is but I can't find it不太确定是否有重复的问题,可能是,但我找不到

I've got this code here ( models.py )我在这里有这段代码( models.py

# Create your models here.
class UserProfileInfo(models.Model):
    # Create relationship (don't inherit from User!)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Add any additional attributes you want
    can_view_all = models.BooleanField(default=True)
    can_edit_all = models.BooleanField(default=False)

    can_add_admin = models.BooleanField(default=False)
    alias = models.CharField(default='none')

    @property
    def alias(self):
        return models.CharField(default=self.user.username)

    def __str__(self):
        # Built-in attribute of django.contrib.auth.models.User !
        return self.user.username

    @alias.setter
    def alias(self, value):
        self._alias = value

As you can see, I'm trying to grab the username with the alias property, but it doesn't work, can someone help me, Basically, I'd like to be able to edit the boolean fields later on (I can do that) but I don't know which user I'm editing if there is a way to get the username directly via HTML injection that would be even better, but I just need a way to show which user I'm editing如您所见,我正在尝试使用别名属性获取用户名,但它不起作用,有人可以帮助我吗,基本上,我希望稍后能够编辑 boolean 字段(我可以那)但我不知道我正在编辑哪个用户,如果有办法通过 HTML 注入直接获取用户名,那会更好,但我只需要一种方法来显示我正在编辑的用户

By the way, it isn't always the same user I'm signed in as, so I can't just use user顺便说一句,我登录的用户并不总是同一个用户,所以我不能只使用用户

Thank you谢谢

Edit: Views.py编辑: Views.py

@method_decorator(login_required, name='dispatch')
class UserUpdateView(UpdateView):
    context_object_name = 'userprofileinfo'
    fields = ('can_view_all', 'can_edit_all', 'can_add_admin')
    model = models.UserProfileInfo

In Django, to reference a field in a foreign key object, you have to use the double underscore syntax, like this - user__username在 Django 中,要引用外键 object 中的字段,您必须使用双下划线语法,例如 - user__username

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM