skip to Main Content

I’m having trouble sending data from my main.js back to django so that it can be processed there and the database can be updated. The user who is logged in can manipulate the data given by the WorkshopMasterView within in the template/frontend. By submitting the data the current JSON-object needs to be send back to django for processing.

I receive the following error messages:

main.js:379 POST http://127.0.0.1:8000/workshop-master-view/ 404 (Not Found)
    sendJsonToServer    @   main.js:379
    (anonymous) @   main.js:420

Here is the underlying logic:

path("workshop/", WorkshopMasterView.as_view(), name="workshop-master-view"),
path('process_json/', ProcessJsonView.as_view(), name='process_json'),


class WorkshopMasterView(generic.ListView):
    model = WorkshopSpaceRequest
    template_name = 'management/workshop_master.html'
    context_object_name = 'data'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        datum = self.request.GET.get('datum')
        
        try:
            date_obj = datetime.strptime(datum, '%d.%m.%Y').date() if datum else datetime.today().date()
        except ValueError:
            date_obj = datetime.today().date()

        workshop_spaces = WorkshopSpace.objects.all()
        
        current_user = self.request.user
        if current_user.is_authenticated:
            current_user_data = {
                "acronym": str(current_user.acronym),
                "cost_center": current_user.cost_center,
                "user_id": current_user.username,
                "user_first_name": current_user.first_name,
                "user_last_name": current_user.last_name,
            }
        else:
            current_user_data = {
                "acronym": 0,
                "cost_center": 0,
                "user_id": 0,
                "user_first_name": 0,
                "user_last_name": 0,
            }

        data = {
            "date": date_obj.strftime('%Y-%m-%d'),
            "current_user": current_user_data,
            "rooms": []
        }

        for space in workshop_spaces:
            room_data = {
                "name": space.workshop_space_number,
                "workshop_space_size": str(space.workshop_space_size),
                "availability_electricity": str(space.availability_electricity),
                "availability_wifi": str(space.availability_wifi),
                "availability_lifting_ramp": str(space.availability_lifting_ramp),
                "availability_workplace": str(space.availability_workplace),
                "time_slots": {
                    "0000-0300": 0,
                    "0300-0600": 0,
                    "0600-0900": 0,
                    "0900-1200": 0,
                    "1200-1500": 0,
                    "1500-1800": 0,
                    "1800-2100": 0,
                    "2100-0000": 0
                }
            }

            requests = WorkshopSpaceRequest.objects.filter(workshop_space=space, date=date_obj)
            for request in requests:
                time_slot_data = {
                    "user": {
                        "acronym": str(request.user.acronym),
                        "cost_center": request.user.cost_center,
                        "user_id": request.user.username,
                        "user_first_name": request.user.first_name,
                        "user_last_name": request.user.last_name
                    }
                } if request.user else None
                room_data["time_slots"][request.time_block] = time_slot_data

            data["rooms"].append(room_data)

        context.update({
            'datum': datum,
            'data': data,
        })

        print(context['data'])
        
        return context

class ProcessJsonView(View):
    @method_decorator(csrf_exempt, name='dispatch')
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body)

            date_str = data.get('date')
            date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
            rooms = data.get('rooms', [])

            for room in rooms:
                room_name = room.get('name')
                time_slots = room.get('time_slots', {})

                workshop_space = WorkshopSpace.objects.get(workshop_space_number=room_name)

                for time_slot, user_data in time_slots.items():
                    if user_data != 0:
                        user_id = user_data['user']['user_id']
                        user = CustomUser.objects.get(username=user_id)

                        WorkshopSpaceRequest.objects.update_or_create(
                            workshop_space=workshop_space,
                            date=date_obj,
                            time_block=time_slot,
                            defaults={
                                'user': user
                            }
                        )
                    else: 
                        WorkshopSpaceRequest.objects.filter(
                            workshop_space=workshop_space,
                            date=date_obj,
                            time_block=time_slot
                        ).delete()

            return HttpResponseRedirect(f'/management/workshop_master/?datum={date_str}')

        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)


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.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function sendJsonToServer(data) {
    const csrftoken = getCookie('csrftoken');

    fetch('/workshop-master-view/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.redirected) {
            window.location.href = response.url;
        } else {
            return response.json();
        }
    })
    .then(data => {
        if (data) {
            console.log('Erfolgreich:', data);
        }
    })
    .catch((error) => {
        console.error('Fehler:', error);
    });
}

document.getElementById('confirm-button').addEventListener('click', () => {
    const scheduleContainer = document.getElementById('schedule-container');
    let dataJson = scheduleContainer.getAttribute('data-context');

    dataJson = dataJson.replace(/'/g, '"');

    let data;
    try {
        data = JSON.parse(dataJson);
    } catch (error) {
        console.error('Fehler beim Parsen der JSON-Daten:', error);
        return;
    }

    sendJsonToServer(data);
});


{
    "date": "2024-06-23",
    "current_user": {
        "acronym": "XYZ",
        "cost_center": "",
        "user_id": "ABCDEF",
        "user_first_name": "ABC",
        "user_last_name": "DEF"
    },
    "rooms": [
        {
            "name": "711_2_1",
            "workshop_space_size": "200.00",
            "availability_electricity": "True",
            "availability_wifi": "True",
            "availability_lifting_ramp": "True",
            "availability_workplace": "False",
            "time_slots": {
                "0000-0300": 0,
                "0300-0600": 0,
                "0600-0900": 0,
                "0900-1200": 0,
                "1200-1500": 0,
                "1500-1800": 0,
                "1800-2100": 0,
                "2100-0000": {
                    "user": {
                        "acronym": "RD/XYZ",
                        "cost_center": "",
                        "user_id": "ABCDEF",
                        "user_first_name": "ABC",
                        "user_last_name": "DEF"
                    }
                }
            }
        },
        {
            "name": "711_2_2",
            "workshop_space_size": "20.00",
            "availability_electricity": "True",
            "availability_wifi": "True",
            "availability_lifting_ramp": "False",
            "availability_workplace": "False",
            "time_slots": {
                "0000-0300": 0,
                "0300-0600": 0,
                "0600-0900": 0,
                "0900-1200": 0,
                "1200-1500": 0,
                "1500-1800": 0,
                "1800-2100": 0,
                "2100-0000": 0
            }
        }
    ]
}

2

Answers


  1. Chosen as BEST ANSWER

    thanks for the quick reply. Yes i use the following namespace:

    app_name = 'management'
    
    urlpatterns = [
        path("", LandingView.as_view(), name="landing-view"),
        path("building/", BuildingListView.as_view(), name="building-list-view"),
        path("workshop/", WorkshopMasterView.as_view(), name="workshop-master-view"),
        path('process_json/', ProcessJsonView.as_view(), name='process_json'),
    ]
    

    I changed the fetch-URL to:

    function sendJsonToServer(data) {
        const csrftoken = getCookie('csrftoken');
    
        fetch("{% url 'management:workshop-master-view' %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify(data)
        })
        .then(response => {
            if (response.redirected) {
                window.location.href = response.url;
            } else {
                return response.json();
            }
        })
        .then(data => {
            if (data) {
                console.log('Erfolgreich:', data);
            }
        })
        .catch((error) => {
            console.error('Fehler:', error);
        });
    }
    

    But still get same error msg:

    POST http://127.0.0.1:8000/management/workshop/%7B%%20url%20'management:workshop-master-view'%20%%7D 404 (Not Found)


  2. workshop-master-view is the name of a URL pattern, not the actual endpoint URL. You should either use the {% url 'workshop-master-view' %} template tag or pass workshop/ as the URL to the fetch method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search