D
D
Danila2020-01-25 13:47:21
Django
Danila, 2020-01-25 13:47:21

How to make an image load by URL in Django?

Good afternoon, I need to implement a file upload form where you can upload a file either from a computer or by URL in Django.
I managed to implement the download from the computer, but I do not understand how to do it through the URL.
Please send.
forms.py

class ImageForm(ModelForm):

    class Meta:
        model = Images
        fields = ['image', 'url']

models.py
class Images(models.Model):

    image = models.ImageField(
        verbose_name='Image file',
        unique=True
    )

    url = models.URLField(
        unique=False,
        blank=True
    )

views.py
class UploadView(View):
    def get(self, request):

        form = ImageForm()

        context = {
            'form': form
        }

        return render(request, 'upload.html', context)

    def post(self, request):

        form = ImageForm(request.POST, request.FILES)
        context = {
            'form': form
        }

        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/")
        else:
            render(request, 'upload.html', context=context)

Now the page looks like this with this code.
5e2c1c9021c98639186888.png

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