Grab username of User from model django

149 views Asked by At

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)

# 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

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

@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
1

There are 1 answers

1
Prashant On

In Django, to reference a field in a foreign key object, you have to use the double underscore syntax, like this - user__username