How to upload multiple images or files to database through django model form submission.

How to upload multiple images or files to database through django model form submission.

Deep Narayan Tandan

The reason you’re reading this because you are probably developing a blog or portfolio album using Django and donot want to upload images or files in database one by one.

It’s something I actually was searching all over the internet from last 10 days when I was developing one photographer portfolio site using django, and couldn’t find examples online. Took me days, but I finally figured it out.


You can find the codes on my github gist link :- SourceCode

My model, views, urls and html file is as below.

One for the Categories,other for Event Name and the other would be for the Images related to each event names.

Your Images model would have a ForeignKey to the eventname model.

models.py
forms.py
urls.py

views.py
upload.html
Points to be remembered:-
  • For using in production server , if you are using nginix and gunicorn then increase your nginx upload size to your requirement by editing the nginx.conf file
nano /etc/nginx/nginx.conf

Now add the following code in it:

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so :

http {
    client_max_body_size 8M;

    //other lines...
}

Restart Nginix now:

sudo service nginx restart


  • Do not forget to pass all the fileds of forms as cleaned data while running the loop to save the images in database in views.py
  • For showing content in frontend file use if statements to sort out the particular eventname and their image fields.


For any suggestions and correction, comment on github gist link.

Happy Coding:)



Report Page