Upload Files/Images in Django

Upload images and files in django

To add images into your database, add the below code in your model.

    image = models.ImageField(upload_to=get_file_path,null=True,blank=True)

Images can have the same name in some cases and that will cause to unfavourable conditions. So let's create a unique name for images. We are going to add the current dateTime in the image name. Below is the code for doing this operation.

import datetime
def get_file_path(requestfilename):
    filename_original = filename
    nowTime = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
    filename = "%s%s" % (nowTime, filename_original)
    return os.path.join('uploads/', filename)

 Open the settings.py file and add the below code:

MEDIA_URL = '/images/'

MEDIA_ROOT =  os.path.join(BASE_DIR, 'media')

Open the project's urls.py file and paste the below code:

from django.conf import settings
from django.conf.urls.static import static

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

Now we have to make the form to accept input. I am using model forms and below given is the code.

<form action="" method='POST' enctype = "multipart/form-data">
    {% csrf_token %}
    <div class="card">
        <div class="card-header bg-dark text-center text-white">
            <h3 class="">Add Blog</h3>
        </div>
        <div class="card-body">
            {{form.as_p}}
        </div>
    </div>
    <button class="btn btn-primary btn-sm"> Save</button>
</form>

Note : If you are editing an existing form, always remember to add the enctype="multipart/form-data" for accepting the images. Add the csrf_token whenever sending data from the form.

In your views.py file, inside the function where you have written the code to insert data, add the below code:

def addblog(request):
    form = BlogForm()
    if request.method == "POST":
        form = BlogForm(request.POST, request.FILES)
        form.save()
        messages.success(request, "Blog added successfully")
        return redirect('/')

    context = {'form':form}
    return render(request, 'post/add.html', context)


© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT