G
G
gromyko212020-10-21 13:04:46
Django
gromyko21, 2020-10-21 13:04:46

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>

The log outputs the content of the html page I'm linking to. Although if I display item, it shows me the name of the file being loaded
view of the page for processing files
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})">

I tried to fill out the template on this page and download from it, there, if everything works. And I need the photo to be loaded when you click on the input in the template with a chat.
According to my scheme, the photo does not load at all.
Model
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 question

Ask a Question

731 491 924 answers to any question