简体   繁体   中英

Display User's Django Rest Framework Auth token in templates

I recently implemented Django Rest Framework into my project, and I was wondering if it is possible for me to display the Token that has the associated User object attached to it.

So if I, for example could do this in the templates: {{ user.token }}.

You can display the token using templates {% csrf_token %}

and Python code as well using get_token(request) .

Documentation: https://docs.djangoproject.com/en/3.0/ref/csrf/

You can write middleware For example:

class GetUsrTokenMiddleware(MiddlewareMixin):
FORWARDED_FOR_FIELDS = [
    'HTTP_X_FORWARDED_FOR',
    'HTTP_X_FORWARDED_HOST',
    'HTTP_X_FORWARDED_SERVER',
]

def process_view(self, request, view_func, view_args, view_kwargs):
    if hasattr(request, 'user'):
        if request.user.is_authenticate():
            token, created = Token.objects.get_or_create(user=request.user)
            setattr(request.user,'token',token.key)
    return None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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