简体   繁体   English

在Django中使用扩展用户模型中的用户名检索用户详细信息

[英]Retrieving user details using username from extended User Model in Django

I'm trying to retrieve the details of a user using the username test from an extended User model in Django. 我正在尝试使用用户名测试从Django中扩展的用户模型中检索用户的详细信息。 But I am unable to do it. 但是我做不到。 It's giving me the error: 这给了我错误:

ValueError at / invalid literal for int() with base 10: 'test' 以10为底的int()值无效的int()的ValueError:'test'

Following is my code: 以下是我的代码:

models.py models.py

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

views.py views.py

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: 现在签名Auth():

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

I'm retrieving the user details using username: test in signatureAuth() method. 我正在使用username检索用户详细信息 signatureAuth()方法中的test test is already present in my User as well as DocchainUser model. 我的用户以及DocchainUser模型中已经存在测试

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; 请注意,您在此处苦苦挣扎的原因之一是您的OneToOneField可能被错误命名。 the relationship is with the entire model, not the username; 关系与整个模型有关,而不与用户名有关; you should call it just docchainuser . 您应该将其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.) (还请注意,您的if user.is_authenticated是没有意义的;它只是检查用户是User的实例,而不是AnonymousUser的实例,您知道这是因为您只是从User模型中明确检索了它。)

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

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