Jkennedy559
Jkennedy559

Reputation: 133

How to display image from Django form ImageField input without models/database

I'm trying to display an image from a form ImageField on my template once the user has actioned the form. All the previous examples I have read about revolve around saving the image as a static file. Is this necessary? Is it possible to pass the image from the form through a view back onto a template without interaction with the database?

I am not using any models and instead, my goal is to send the image to a restful API for classification and display it.

### forms.py

from django import forms

class FileForm(forms.Form):
    image = forms.ImageField(help_text="Upload image: ", required=False)
### home_template.py

<h2>Tower Predictor</h2>
<form method="post" enctype='multipart/form-data'>
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

# Display image 
{% if image %}
<img src="{{ image.url }}" alt="img">
{% endif %}
### views.py
from django.shortcuts import render
import requests
from .forms import FileForm


def home(request):
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            image = request.FILES['image']
            form = FileForm()
            context = {'form': form, 'image': image}
            return render(request, 'web_ui/home.html', context)
    else:
        form = FileForm()
    return render(request, 'web_ui/home.html', {'form': form})

Upvotes: 2

Views: 3920

Answers (1)

Jkennedy559
Jkennedy559

Reputation: 133

Solved by creating data-uri from image and passing to the template.

### views.py
from django.shortcuts import render
import requests
from .forms import FileForm
from base64 import b64encode


def home(request):
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['image']
            data = file.read()
            # Calling .decode() converts bytes object to str
            encoded = b64encode(data).decode()
            mime = 'image/jpeg;'
            context = {"image": "data:%sbase64,%s" % (mime, encoded)}
            return render(request, 'web_ui/home.html', context)
    else:
        form = FileForm()
    return render(request, 'web_ui/home.html', {'form': form})

Upvotes: 1

Related Questions