POST data only if you are authenticated user- django rest framework

models.py

class OpeningHours(models.Model):
    day_of_week = models.IntegerField(choices=((0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday')))
    opening_time = models.TimeField()
    closing_time = models.TimeField() 

serializer.py

class OpeningHoursSerializer(serializers.ModelSerializer):
    class Meta:
        model = OpeningHours
        fields = '__all__'
        read_only_fields = ("user",)

views.py

class OpeningHoursViewSet(viewsets.ModelViewSet):
    queryset = OpeningHours.objects.all()
    serializer_class = OpeningHoursSerializer
    authentication_classes = [CustomAuthentication]
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

authentication.py

class CustomAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        username = request.META.get('HTTP_USERNAME')
        if not username:
            return None
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')
        return (user, None)

I want only authenticated user to be able to perform POST method . I have set the key as HTTP_USERNAME and value as username (which i have created in django admin) on postman header before making a post request but im still getting error: "detail": "Authentication credentials were not provided." } How so i solve this.

Rather than using username you can use jwt authentication and use it as a token in your header and send a post request to your server where it will be handled with the use of permissions class where it verifies the token and handles request

You can join our discord server where we do cool projects

https://discord.com/invite/yQxDSSevc8

Back to Top