0

Whenever I try to make a POST request, the url automatically redirects to the login resulting in BAD_REQUEST

This is my code for login:

class LoginView(View):
  def get(self, *args, **kwargs):
    form = LoginForm()
    context = {
      'form':form
    }
    return render(self.request, 'core/login.html', context)

  def post(self, *args, **kwargs):
    form = LoginForm(self.request.POST or None)
    if form.is_valid():
      email = form.cleaned_data['email']
      password = form.cleaned_data['password']
      user = authenticate(self.request, email=email, password=password)
      if user is None:
        messages.add_message(self.request, messages.ERROR, 'Enter valid email or password')
        return redirect('login')
      login(self.request, user=user)
      return redirect('home')
    return redirect('login')

This is my post function for api:

class NoteCreateView(LoginRequiredMixin, APIView):
  def post(self, *args, **kwargs):
    print(self.request.user)
    data = (self.request.data)
    data['id'] = self.request.user.id
    print(data)
    serializer = NoteSerializer(data=data)
    if serializer.is_valid():
      serializer.save()
      return Response(serializer.data, status=HTTP_201_CREATED)
    return Response(serializer.data, status=HTTP_400_BAD_REQUEST)

And this is the POST request made from frontend

  e.preventDefault()
  const note = document.getElementById('add-note').value
  let date = new Date()
  const data = {
    'note':note,
    'date_created':date
  }
  let url = 'http://localhost:8000/api/notes/create/'
  fetch(url, {
    method:'POST',
    headers:{
      'content-type':'application/json',
      'X-CSRFToken':csrftoken
    },
    body:JSON.stringify(data)
  })
  .then(res => {
    getAllNotes()
    document.getElementById('form').reset()
  })
})

The url that it always redirects on making POST request /login/?next=/api/notes/create/

urls.py

api:

urlpatterns = [
    path('notes/', NoteListView.as_view(), name='all'),
    path('notes/create/', NoteCreateView.as_view(), name='create')
]

frontend

urlpatterns = [
    path('register/', RegisterView.as_view(), name='register'),
    path('login/', LoginView.as_view(), name='login'),
    path('', HomeView.as_view(), name='home'),
    path('logout/', LogoutView.as_view(), name='logout')
]

settings.py

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'

1 Answers1

0

You should make use of authentication_classes and permission_classes of the Django Rest Framework. Check it out here: https://www.django-rest-framework.org/api-guide/authentication/

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'user': str(request.user),  # `django.contrib.auth.User` instance.
            'auth': str(request.auth),  # None
        }
        return Response(content)

Plus I can highly recommend you the to use a JWT token with following package: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/

Like that you can get rid of your Login View:

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]
jojacobsen
  • 23
  • 4