OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

django: Sending JSON-Data from within main.js back to view for processing/updating database

  • Thread starter Thread starter TheHotch
  • Start date Start date
T

TheHotch

Guest
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:

Code:
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:

Code:
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
            }
        }
    ]
}

<p>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.</p>
<p>I receive the following error messages:</p>
<pre><code>main.js:379 POST http://127.0.0.1:8000/workshop-master-view/ 404 (Not Found)
sendJsonToServer @ main.js:379
(anonymous) @ main.js:420
</code></pre>
<p>Here is the underlying logic:</p>
<pre><code>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.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
}
}
]
}
</code></pre>
 
Top