Answer the question
In order to leave comments, you need to log in
Uploading django-channels-websocket files?
Good afternoon. I can't figure out how to upload files to the chat page. As I understand it, they need to be loaded on another page, and the address must be transferred to the sockets.
js
<input id="upload" type="file" onchange="selectFile()">
<script>
function selectFile() {
e = document.getElementById('upload')
if(e.files[0]) {
let item = e.files[0];
let filesize = item.size;
let filesizeMB = (filesize / (1024 * 1024)).toFixed(2);
if (filesizeMB >= 3) {
alert('Максимальный размер фотографии 3 мб');
} else {
var $input = $("#uploadimage");
var fd = new FormData;
fd.append('image_message', item);
fd.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
url: '/chat/upload/',
type: 'POST',
data: fd,
processData: false,
contentType: false,
<!-- csrfmiddlewaretoken: '{{ csrf_token }}',-->
success: function (data) {
console.log(data);
}
});
}
} else {
alert('Файл не найден');
}
}
</script>
def upload_private_chat(request):
if request.method == 'POST':
message_form = MessageForm(request.POST, request.FILES)
if message_form.is_valid():
# message_form.instance.author = request.user_id
# message_form.instance.recipient = request.room_id
message_form.save()
else:
pass
else:
message_form = MessageForm()
return render (request, 'chat/upload.html', {'message_form': message_form})">
class Message(models.Model):
author = models.ForeignKey(User, verbose_name="Отправитель", on_delete=models.CASCADE)
recipient = models.ForeignKey(Chat, related_name='received_messages', verbose_name="Получатель", on_delete=models.CASCADE)
content = models.TextField("Сообщение", default='Нет сообщения')
image_message = models.ImageField(null=True, blank=True, upload_to="message_image", verbose_name='Изображения в сообщениях')
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question