Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework Web Login not working

I can't seem to figure out why my rest framework login in my django project won't work... I have got the log in link there and all and it does redirect me to the rest login page but after filling in my credentials and clicking login it just takes me back to the page I came from but it does not seem to authenticate me as it still says "Login" in the top right corner...

This is the login button I am talking about.

I would expect it to change to "admin" in this case as I am trying to login using my superuser named "admin"...

I am surely missing something..

Here are my REST Urls

path("rest/auctions", auction_list, name="auction-list"),
path('rest/auctions/<int:pk>', auction_detail, name="auction-detail"),
path('rest-auth/', include('rest_framework.urls', namespace='rest_framework')),

The rest-auth/ one I know is the one that somehow adds the login button and all (Magic?) But maybe I have to do something else too to make it authenticate? I don't know... I am using the built in django authentication system and User model.

views.py

@api_view(['GET'])
def auction_list(request, format=None):
    if request.method == 'GET':
        query = request.GET.get('q')
        if query is not None:
            auctions = Auction.objects.filter(Q(title__icontains=query), deadline__gte=timezone.now(),
                                              status=Auction.STATUS_ACTIVE)
        else:
            auctions = Auction.objects.all()
        serializer = AuctionSerializer(auctions, many=True, context={'request': request})
        return Response(serializer.data)

serializer.py

class AuctionSerializer(serializers.ModelSerializer):
    winning_bid = serializers.SlugRelatedField(many=False, read_only=True, slug_field='amount', allow_null=True)
    seller = serializers.SlugRelatedField(many=False, read_only=True, slug_field='username', allow_null=False)

    class Meta:
        model = Auction
        fields = ('id', 'url', 'title', 'description', 'deadline', 'min_price', 'winning_bid', 'seller')

in my Settings.py

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
    ],
}

Lastly I can mention that the authentication works when I use the API via Postman.

like image 288
Matheos Avatar asked Oct 24 '18 17:10

Matheos


1 Answers

If the other solution doesn't work, add this line too

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
),
like image 68
areema Avatar answered Sep 29 '22 05:09

areema