1

here is my view for login functionality


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')    
    
    def post(self, request):
        print('in post')
        data = {
            'username': request.POST['username'], 
            'password': request.POST['password']
        }
        url = "http://127.0.0.1:8000/api/v1/login/"
        response = requests.post(url, data=data)
        print(response, 'res????')
        if response.status_code == 200:
            return redirect('dashboard')
        return render(request, 'login.html')

my problem is that i got Forbidden (CSRF cookie not set.): /endpoint/

how can i configure csrf functionality to make successful call and get response from the api which is again developed in same application

thank you in advance !!

2
  • An API is normally exempt from CSRF tokens. But it will here not make much difference: Django's authentication relies on the session, you query the API with a different session (well in fact, no session at all). Commented Apr 3, 2024 at 13:09
  • Exactly how does the login.html looks like? Commented Apr 3, 2024 at 13:17

1 Answer 1

0

In the form you need to send the CSRF-token, so, the form looks like:

<form method="post" action="{% url … %}">
  {% csrf_token %}
  <button type="submit">login in</button>
</form>

where you specify the url of the endpoint. But the post function will not work. Indeed, Django normally works session-oriented to log in a user, but the session of your requests.post(…) is a different session then the one with which you render templates and communicate with the browser. Most APIs don't even work with sessions, but with tokens that are send with each request for example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.