[英]Django REST Framework Auth Token
I'm having a little trouble with Token Authentication in the Django REST Framework. 我在Django REST Framework中遇到令牌验证问题。 From the docs I know it is a matter of implementing the following:
从我知道的文档来看,这是实现以下内容的问题:
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=...)
print token.key
Now my question is, what exactly goes in the argument of Token.objects.create(user=...)
. 现在我的问题是,
Token.objects.create(user=...)
的论点到底是什么。 The answer here helps and it says That will provide a Token model which is foreign-keyed to User. 这里的答案有所帮助,它说它将提供一个外键键入用户的令牌模型。 I'm not sure I understand this.
我不确定我明白这一点。
I have my own model of Users defined like so: 我有自己的用户模型,如下所示:
class Users(models.Model):
userid = models.IntegerField(primary_key=True)
username = models.CharField(max_length=255L, unique=True, blank=True)
email = models.CharField(max_length=255L, unique=True, blank=True)
password = models.CharField(max_length=64L, blank=True)
registeredip = models.CharField(max_length=255L, blank=True)
dob = models.DateField(null=True, blank=True)
firstname = models.CharField(max_length=255L, blank=True)
lastname = models.CharField(max_length=255L, blank=True)
joindate = models.DateTimeField()
class Meta:
db_table = 'Users'
How would I create a token for users that satisfy certain conditions in this case? 在这种情况下,如何为满足某些条件的用户创建令牌?
# View Pseudocode
from rest_framework.authtoken.models import Token
def token_request(request):
if user_requested_token() and token_request_is_warranted():
new_token = Token.objects.create(user=request.user) #What goes here?
Any help or leads to any more documentation/examples would really help me out here. 任何帮助或导致任何更多的文档/示例将真正帮助我在这里。 Thank you!
谢谢!
to be sure: we are talking about Token authentication that is provided by django rest framework? 可以肯定:我们正在谈论由django rest框架提供的令牌认证?
If so, this is very simple method, where there is a token (random 40 characters) that is used instead of username and password. 如果是这样,这是一个非常简单的方法,其中有一个令牌(随机40个字符),而不是用户名和密码。
What is DRF delivering is a table ( Token
) where you need to create entries for your users, Token
is referencing your user model (builtin or active custom model). 什么是DRF交付是一个表(
Token
),您需要为您的用户创建条目, Token
引用您的用户模型(内置或活动自定义模型)。
There are no tokens created initially, you need to create them. 最初没有创建令牌,您需要创建它们。
There are several ways to create tokens, most common are: 有几种创建令牌的方法,最常见的是:
Basically that mean, that somewhere in your code you need to create Token
instance, referencing your user instance. 基本上这意味着,您需要在代码中的某处创建
Token
实例,引用您的用户实例。
Token(user=user).save()
Now, few remarks: 现在,几句话:
ps python class names should be singular (Users->User) ps python类名应该是单数的(Users-> User)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.