Django URL 404 - 1 неделя потрачена на отладку с GPT4, не повезло. Одна конкретная функция просто НЕ разрешается

Краткое описание проблемы: Я столкнулся с проблемой, когда URL /LS/mark-text-responses/ в моем Django-приложении не находится, когда AJAX-запрос отправляется на представление mark_text_responses. Эта проблема возникает в пользовательской части моего приложения, а именно в коде JavaScript, который отправляет AJAX-запрос. Я получаю ошибку 404 Not Found, указывающую на то, что URL не разрешается корректно.

Релевантный код JavaScript:

**javascript **


function submitWorksheet(event, activityIndex) {
    event.preventDefault();
    const worksheetForm = event.target;
    const worksheetQuestionsData = worksheetForm.querySelector('.worksheet-questions').textContent;
    let worksheetData = {};
    try {
        worksheetData = JSON.parse(worksheetQuestionsData);
    } catch (error) {
        console.error('Error parsing worksheet data:', error);
        return;
    }
    // ... (code omitted for brevity) ...
    if (question.type === 'text_response') {
        const textResponse = worksheetForm.querySelector(`textarea[name="response_${index + 1}"]`).value;
        const feedbackElement = document.getElementById(`text-response-feedback-${index + 1}`);
        // Make an AJAX request to the server to get feedback on the text response
        fetch('/lessons/mark-text-responses/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value
            },
            body: JSON.stringify({
                activity_id: '{{ activity.id }}',
                question_index: index,
                text_response: textResponse
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.feedback) {
                feedbackElement.textContent = data.feedback;
            } else {
                console.error('Error:', data.error);
                feedbackElement.textContent = 'Error processing text responses.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            feedbackElement.textContent = 'Error processing text response.';
        });
    }
}


Релевантный код на Python / Django:

python



# LM/urls.py
urlpatterns = [
    # ...
    path('mark-text-responses/', views.mark_text_responses, name='mark_text_responses'),
    # ...
]


LM/views.py

def mark_text_responses(request):
    if request.method == 'POST':
        # Process the request
        # ...
        return JsonResponse({'error': 'Invalid request method'}, status=400)

Что мы знаем наверняка:

The /LS/mark-text-responses/ URL pattern is correctly defined in the LM/urls.py file.
The mark_text_responses view is defined in the LM/views.py file.
The Django server is running, and other URLs are accessible.
The AJAX request is being sent from the JavaScript code, including the CSRF token in the request headers.

Я В ТУПИКЕ.

На фронтэнде есть кнопка с надписью "submit worksheet". С точки зрения функциональности ничего не происходит, кроме того, что консоль py показывает 404 :(

)

Опробованные шаги:

Checked the URL pattern in the LM/urls.py file to ensure the /LS/mark-text-responses/ URL is correctly defined.
Verified the mark_text_responses view in the LM/views.py file.
Tried debugging the Django server by adding print statements to the mark_text_responses view.
Attempted to access the /LS/mark-text-responses/ URL directly in the browser.

Ожидается: Ожидалось, что вызов функции отправки рабочего листа сделает что-нибудь, кроме возврата 404...

Опробованные шаги:

Checked the URL pattern in the LM/urls.py file to ensure the /LS/mark-text-responses/ URL is correctly defined.
Verified the mark_text_responses view in the LM/views.py file.
Tried debugging the Django server by adding print statements to the mark_text_responses view.
Attempted to access the /LS/mark-text-responses/ URL directly in the browser.

Ожидается: Ожидалось, что вызов функции отправки рабочего листа сделает что-нибудь, кроме возврата 404...

Вернуться на верх