No, not in your models.py -- on the models side of things, all you need to do is include the appropriate app (rest_framework.authtoken
) in your INSTALLED_APPS
. That will provide a Token model which is foreign-keyed to User.
What you need to do is decide when and how those token objects should be created. In your app, does every user automatically get a token? Or only certain authorized users? Or only when they specifically request one?
If every user should always have a token, there is a snippet of code on the page you linked to that shows you how to set up a signal to create them automatically:
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
(put this in a models.py file, anywhere, and it will be registered when a Django thread starts up)
If tokens should only be created at certain times, then in your view code, you need to create and save the token at the appropriate time:
# 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)
Once the token is created (and saved), it will be usable for authentication.
post_save
? – Totally