0

I want to store the imaage in django but unable to do it. This is what i tried..

upload.html

<form name="saveImage" enctype="multipart/form-data" action="{% url 'Reports:saveimage'%}" method="post">
    {% csrf_token %}
    <div style = "max-width:470px;">

        <center>
            <input type = "file" style = "margin-left:20%;"
                   placeholder = "Picture" name = "picture" />
             <input type="submit" value="Store"></input>
        </center>
    </div>

</form>

model.py

def vo_image_upload(inatance,filename):
    return os.path.join('Volunteer',filename)

class Volunteer(models.Model):
    myphoto = models.ImageField(db_column='MyPhoto', upload_to=vo_image_upload, blank=True, null=True)

views.py

def saveimage(request):
    image= request.FILES['picture']
    vo = Volunteer.objects.using('NSS_VO').update(myphoto=image).
    return HttpResponse("<h1>Success</h1>")

Update is used because I am storing image after registration. This code is only saving the File name to myphoto field in database but not storing the image in media folder of Project/project/media/.

Project/Project/url.py

from django.conf.urls import url ,include
    from django.contrib import admin
    from django.conf import settings
    from django.conf.urls.static import static

    urlpatterns = [
        url(r'^ReportsData/', include('Reports.urls')),
    ]

    if settings.DEBUG :
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

and above upload.html ,views.py , models.py belongs to app Reports. What changes I have to do to store the images successfully

Rajadip
  • 2,799
  • 2
  • 11
  • 15
  • Does this answer your question? [Programmatically saving image to Django ImageField](https://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield) – Boris Verkhovskiy Jan 24 '20 at 21:30

1 Answers1

3

You can't do this with update(), as that operates on the database only and wouldn't do any of the actual file saving. You must get the object, assign the file field, and save:

vo = Volunteer.objects.using('NSS_VO').get(id=whatever)
vo.myphoto=image
vo.save()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895