Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display uploaded/chosen image without saving it in database in Django

Tags:

python

django

I'd like to store the image which the user uploads, in a variable within views.py (and apply some opencv operations on it) and then display the resultant image. I don't want to store the image in a database. So, i don't think models are necessary for implementing this. How to proceed further? Following are the index.html and views.py. Sorry if any coding mistakes are there, i'm new to Django.

index.html

<form method="POST" enctype="multipart/form-data">{% csrf_token %}
    <div class="file-field input-field left">
        <div class="btn black-text waves-effect waves-dark" style="background-color: #F5DF73">
            <div>Upload</div>
            <input type="file" name = "input_image" onchange="readURL(this);">
        </div>
        <div class="file-path-wrapper">
           {#<input class="file-path validate" type="text">#}
        </div>
    </div>
    {{ image }}
</form>

views.py

def upload_pic(request):

    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        image = form.cleaned_data['image']

    return render(request, 'html/index.html', {"image": image})

urls.py

urlpatterns = [
    url(r'^$', views.index),
]
like image 969
hulkinBrain Avatar asked Oct 31 '25 02:10

hulkinBrain


1 Answers

Try this

form = ImageUploadForm(request.POST)
image = form.cleaned_data['image']
b64_img = base64.b64encode(image.file.read())

return render(request, 'html/index.html', {"image": b64_img})

In html

<img src="data:image/png;base64,{{image}}">
like image 176
itzMEonTV Avatar answered Nov 01 '25 18:11

itzMEonTV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!