0
saveBtn.addEventListener('click', function() {
        const csrftoken = getCookie('csrftoken');
        fetch('http://localhost:8000/card/{{ auction.slug }}/add/', {
            method: 'GET',
            credentials: 'include',
            headers:{
                'Content-Type':'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': csrftoken,
            }, 
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json(); 
        })
        .then(function(data) {
            if (data.added === true) {
                saveBtn.innerHTML = 'Saved';
            } else {
                saveBtn.innerHTML = ' Save';
            }
        })
        .catch(function(error) {
            console.error('Fetch request failed', error);
        });
    });

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.startsWith(name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

I am sending request to django backend via fetch api. When I try to retrieve the request user,

TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000184986CDE80>>.

it returns an error Why django not authenticating using session id? Should I need to send request.user.id but if send that any user can make requests for other users I think. Or am I sending session id incorrectly to backend?

views.py

def add_to_card(request, slug):
    if request.user.is_anonymous:
        pass
        
    auction = get_object_or_404(Auction, slug=slug)
    user = request.user
    
    data = {'added': False}
    
    card, created = Card.objects.get_or_create(user=user)
    card_item, created = CardItem.objects.get_or_create(card=card, auction=auction)
    
    if created:
        data['added'] = True
    else:
        card_item.delete()
    
    return JsonResponse(data)
7
  • Why are you setting 'Content-Type':'application/json' for a GET request that doesn't even contain a body?
    – CBroe
    Commented Jul 10 at 11:34
  • Have you verified what your request actually sends yet, via your browser dev tools? Check if all the headers and cookies you expected to see there, are actually being transmitted.
    – CBroe
    Commented Jul 10 at 11:35
  • Request header: GET /card/test-image-auction/add/ HTTP/1.1 Accept: / Accept-Encoding: gzip, deflate, br, zstd Accept-Language: en-US,en;q=0.9,uz;q=0.8 Connection: keep-alive Content-Type: application/json Host: localhost:8000 Origin: 127.0.0.1:8000 Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 X-CSRFToken: n5vQQvwJKO3kO1Y8twsscmxGAX81SjXe X-Requested-With: XMLHttpRequest Commented Jul 10 at 11:47
  • Response header: HTTP/1.1 500 Internal Server Error Content-Type: text/html; charset=utf-8 X-Frame-Options: DENY Content-Length: 146600 Vary: origin, Cookie Access-Control-Allow-Origin: 127.0.0.1:8000 Access-Control-Allow-Credentials: true X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Server: daphne Commented Jul 10 at 11:49
  • but why it is not sending cookies? Commented Jul 10 at 11:49

0