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!
Token.objects.create(user=<your user instance>)creates a token for<your user instance>. You can insert this statement into your view where users request tokens passingrequest.userin place of<your user instace>. Make sure thatrequest.useris an instance ofUser, notAnonymousUser.