How to save a picture via a URL in a django model [closed]

We need to develop a service, based on Django framework, which allows you to download images from the user's computer, or by link, and then resize them using the library Pillow. The images should be saved on disk.

I managed to implement the download from the computer, but the link URL does not work.

My model:

from django.db import models


class Image(models.Model):
   title = models.CharField(max_length=200)
   image = models.ImageField(upload_to='images')

   def __str__(self):
      return self.title

My Form:

from django import forms


class ImageForm(forms.Form):
   title_image = forms.CharField(max_length=200, label='Заголовок')
   url_image = forms.URLField(max_length=255, label="URL файла", required=False)
   image_image = forms.ImageField(label='Файл ', required=False)

My View:

from urllib.request import urlopen

import requests
from django.core.files.base import ContentFile, File
from django.core.files.temp import NamedTemporaryFile
from django.shortcuts import render, redirect
from .forms import ImageForm
from .models import Image



def image_upload_view(request):
    """ Загрузка файлов пользователем и обработка"""
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            if request.POST['url_image']:
                print('НЕ ПУСТАЯ УРЛА!')
                url = request.POST['url_image']
                img_temp = NamedTemporaryFile(delete=True)
                img_temp.write(urlopen(url).read())
                img_temp.flush()
                print(img_temp)
                resp = requests.get(url).raw
                print(ContentFile(resp))
                # all_data['image'] = File(img_temp)
                image_save = Image(title=request.POST['title_image'], image=resp)
                image_save.save()
                img_obj = image_save
                return render(request, 'upload_app/index.html', {'form': form, 'img_obj': img_obj})
                #     # url = request.POST['url_image']
                #     #
                #     # # try:
                #     # resp = requests.get(url)
                #     # result = urllib.request.urlretrieve(url)
                #     # print(result)
                #     # image_save = Image(title=request.POST['title_image'], image=ContentFile(resp.content))
                #     # image_save.save()
                #     # img_obj = image_save
                #     # print(f'Это наш рисунок {resp.content}')
                #     # print(f'"POST - {request.POST}')
                #     # return render(request, 'upload_app/index.html', {'form': form, 'img_obj': img_obj})
                #
                #     # except requests.exceptions.RequestException as e:
                #     #     print('Не удалось получить картинку')
                #
            else:
                print(request.POST['title_image'])
                print(request.FILES['image_image'])

                image_save = Image(title=request.POST['title_image'], image=request.FILES['image_image'])
                image_save.save()
                img_obj = image_save
                return render(request, 'upload_app/index.html', {'form': form, 'img_obj': img_obj})
        else:
            form.add_error(None, 'Ошибка валидности')
    else:
        form = ImageForm()
    return render(request, 'upload_app/index.html', {'form': form})

This is the pattern:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Загрузка файлов</title>
</head>
<body>

<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
    <div class="form-error">{{ form.non_field_errors }}</div>

    {% for f in form %}
        <p><label class="form-label" for="{{ f.id_for_label }}">{{f.label}}: </label>{{ f }}</p>
        <div class="form-error">{{ f.errors }}</div>
    {% endfor %}
    <button type="submit">Сохранить на диск</button>
</form>


{% if img_obj %}
  <h3>Файл загружен успешно : {{ img_obj.title }}</h3>
  <img src="{{ img_obj.image.url }}" alt="connect" style="max-height:300px">
  <img src="https://i.ytimg.com/vi/vEYsdh6uiS4/maxresdefault.jpg">
  <p>Оригинальный размер картинки  {{ img_obj.image.width }}x{{ img_obj.image.height }}</p>
{% endif %}
{{ request.FILES }}
</body>
</html>

I'm a beginner, please do not judge) Maybe someone has faced such a problem

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