Retrieving User Details Using Username From Extended User Model In Django

- 1 answer

I'm trying to retrieve the details of a user using the username test from an extended User model in Django. But I am unable to do it. It's giving me the error:

ValueError at / invalid literal for int() with base 10: 'test'

Following is my code:

class DocchainUser(models.Model):
    docchainuser_name = models.OneToOneField(User, on_delete = models.CASCADE, default='x')
    address = models.CharField(max_length=64,unique=True)   

    def __str__(self):
        return self.address

def my_users(request):
    if request.method == 'POST':    
        username = request.POST.get('username') 
        user = authenticate(username=username)
        if user:
            if user.is_authenticated:
                signBool = signatureAuth(username)
                if signBool == 'AUTHENTICATED':
                    login(request, user, backend=settings.AUTHENTICATION_BACKENDS[0])
                    return HttpResponseRedirect('/dashboard')

And the signatureAuth() now:

def signatureAuth(username):  
    userModel = DocchainUser.objects.filter(docchainuser_name=username)
    address = userModel.address

I'm retrieving the user details using username: test in signatureAuth() method. test is already present in my User as well as DocchainUser model.



You don't have an extended user model, you have a separate model with a one-to-one relation to User. So in order to query that model by username, you need to follow the relationship.

userModel = DocchainUser.objects.filter(docchainuser_name__username=username)

Note, one of the reasons you struggled here is that your OneToOneField is probably misnamed; the relationship is with the entire model, not the username; you should call it just docchainuser.

(Also note, your if user.is_authenticated is pointless; that just checks that the user is an instance of User rather than AnonymousUser, which you know it is because you just explicitly retrieved it from the User model.)