[Answered ]-How to set API keys for non-authentication models in Django?

1๐Ÿ‘

Q1:

Is there some way to generate an authentication token for each outlet?

Is full documented on Customization section. For your code, for example, to have several keys for each outlet:

# stores/models.py
from django.db import models
from rest_framework_api_key.models import AbstractAPIKey

class Store(models.Model):
    name = models.CharField(max_length=128)

class Outlet(models.Model):
    name = models.CharField(max_length=128)
    store = models.ForeignKey(
        Store,
        on_delete=models.CASCADE)

class OutletAPIKey(AbstractAPIKey):
    outlet = models.ForeignKey(
        Outlet,
        on_delete=models.CASCADE,
        related_name="api_keys",
    )

You can manage keys on admin panel.

Q2:

Also, how would I validate this token in the DRF views and/or serializer?

Following programmatic usage documentation should be something like this:

from rest_framework.views import APIView
from rest_framework_api_key.models import APIKey
from rest_framework_api_key.permissions import HasAPIKey

from .models import Project

class ProjectListView(APIView):
    permission_classes = [HasAPIKey]

    def get(self, request):
        """Retrieve a project based on the request API key."""
        key = request.META["HTTP_AUTHORIZATION"].split()[1]
        outlet_api_key = OutletAPIKey.objects.get_from_key(key)
        outlet = outlet_api_key.outlet
๐Ÿ‘คdani herrera

Leave a comment