Skip to content
Advertisement

Django upload multiple images per post

I want to let the user upload multiple images per post. Similarly to an e-commerce platform with multiple images per product. But till now the images are not sent to the database.

That’s my code so far:

models.py:

JavaScript

forms.py:

JavaScript

views.py:

JavaScript

project_form.html:

JavaScript

settings.py:

JavaScript

project urls.py

JavaScript

app urls.py

JavaScript

Advertisement

Answer

Issue:

  1. You have made ProjectForm which relates to Project model, but the image field is in ProjectImage model. So, image field is not even passing to the template and you also haven’t passed it in fields=['title','describtion'] in ProjectFrom.

  2. You haven’t made configurations for saving the media files in project’s urls.py.

Solution:

  1. You should make two forms in forms.py, first ProjectForm which will get the data for Project model and second ProjectImageForm which will get the list of images, then using request.FILES.getlist('image') you can save images which relates to a particular instance one by one in loop as you tried to save.

  2. You should make media configurations in project’s urls.py



Try Below Code:

forms.py

JavaScript

views.py

JavaScript

project_form.html or template file:

JavaScript

project’s urls.py

JavaScript

app’s urls.py

JavaScript

Your models.py and settings.py can be remain same, but it’s recommended to use MEDIA_URL = 'media/' and MEDIA_ROOT = os.path.join(BASE_DIR, 'media/'), then you should make nested folders inside it to save images or any files.

Note: You should always return HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it’s a good practice in general as stated in the tutorial4.

Note: Function based views are generally written in snake_case not camelCase, you may change it to create_project from createProject.

Note: Add / at the end of upload_to as upload_to='products/' in FileField in ProjectImage model.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement