How to add multiple images within one django queryset that will have a image field? It can be done through foreignkey but if i use different table for image then id’s will be generated differently
Can anyone help me on how exactly i can upload multiple images on one django queryset? Example: We can upload multiple images in one post Facebook
Advertisement
Answer
The most common way to go about implementing a many-to-one relation is to create another table and connect it through a foreign key. You can do something like this in your models.py :
class Post(models.Model): title = models.CharField(max_length=250) image = models.FileField(blank=True) class Images(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'images/')
Here, attribute post of class Images will be used to connect the images to their respective posts. In views.py, you can filter images based on the foreign key attribute in this manner :
def detail_view(request, id): post = get_object_or_404(Post, id=id) images = PostImage.objects.filter(post=post) return render(request, 'detail.html', {'post':post,'images':images})
Now, all the images passed as context are the ones which were supposed to be linked to that particular post for you to use in your template.