Problem 1: I made a notes app. I made a login function, that logs in people. I keep getting an error after I log in and try to create a new note, it is saying "403 forbidden error" in the console. But if I dont log in, it works perfectly. Heres the backend code :
@api_view(["POST"])
def login_view(request):
data = request.data
username = data["username"]
password = data["password"]
if request.user.is_authenticated:
return Response("hpr")
else:
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return Response("hpr")
return Response("An error occured, please try again later.")
this is the login view. I have created a model with a foreign key, that might be the problem too.
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, related_name="notes", on_delete=models.CASCADE, null=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
here is the view that creates a note :
@api_view(['POST'])
def createNote(request):
data = request.data
note = Note.objects.create(
body=data['body'],
)
serializer = NoteSerializer(note, many=False)
return Response(serializer.data)
Problem 2: I also have another doubt. I have a function that gets the notes from the database and displays it. I have made the serialised get all the fields of the note model. But when I try to access the "author" field, I am getting an empty array from the frontend(im using react js).
@api_view(["GET"])
def getNotes(request):
notes = Note.objects.all().order_by("-updated")
serializer = NoteSerializer(notes, many=True)
return Response(serializer.data)
I can also confirm it is not the problem of the frontend, I tested the frontend with console.log and it works.
Cause of problem 1 : After testing with postman, I found out that it is the problem with the csrf tokens! I am not sure how to fix it. Please help me.