Fix: исправлена ошибка 403 при загрузке файлов в чат
- Добавлен декоратор @ensure_csrf_cookie в API view - Изменён способ получения CSRF токена: теперь берётся из cookie через getCookie() - Добавлена функция getCookie() в chat_detail.html Причина ошибки: CSRF токен брался из формы вместо cookie при AJAX запросе
This commit is contained in:
parent
cc71038c5e
commit
6df487bd93
@ -5,6 +5,7 @@ from django.contrib.auth.decorators import login_required
|
||||
from django.db import transaction
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.views.decorators.csrf import ensure_csrf_cookie
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from communications.models import (
|
||||
@ -17,6 +18,7 @@ from communications.models import (
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
@ensure_csrf_cookie
|
||||
def upload_message_with_attachments(request):
|
||||
"""Отправка сообщения с вложениями"""
|
||||
chat_id = request.POST.get('chat_id')
|
||||
|
||||
@ -220,6 +220,22 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Функция для получения CSRF токена из cookie
|
||||
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;
|
||||
}
|
||||
|
||||
// Обработка вложений
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const attachDocument = document.getElementById('attachDocument');
|
||||
@ -343,12 +359,14 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
formData.append('chat_id', '{{ chat.id }}');
|
||||
|
||||
const csrftoken = getCookie('csrftoken');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/v1/communications/upload-message/', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
|
||||
'X-CSRFToken': csrftoken
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user