I'm having a little trouble with Token Authentication in the 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=...)
. 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?
If so, this is very simple method, where there is a token (random 40 characters) that is used instead of username and password.
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).
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(user=user).save()
Now, few remarks:
p.s. python class names should be singular (Users->User)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With