How do I attach multiple photos to a post?

  • 0
    Hello everyone!

    There is a model so that when creating a post, the user can attach their photos!

    I see such an option (probably one of the simplest), it is to add an additional model QueryImage, and use inlineformset_factory to make a form for images:

    class Query(models.Model):
        # к этой модели нужно прикрепить фото
        # ...
    
    class QueryImage(models.Model):
        query = models.ForeignKey('Query', related_name='images', verbose_name=u'Запрос')
        image = models.ImageField(u'Фото', upload_to='images/%Y/%m/%d')
        comment = models.CharField(u'Комментарии', max_length=200, blank=True)
        updated = models.DateTimeField(u'Изменен', auto_now=True)
        created = models.DateTimeField(u'Создан', auto_now_add=True)


    Tell me how you can implement such a task in your projects (the task is quite popular)?
    Maybe you are using third-party applications?
    Django Sebastian Medina, Oct 25, 2019

  • 1 Answers
  • 0
    You described a good option.

    Instead of inline, you can throw an API and send photos by AJAX (because, judging by the model, you do not limit the user to a specific number of photos).

    By the way, use django-imagekit to compress photos (you don't know maybe the user would like to send you a 400MB bitmap?)

    And instead of
    image = models.ImageField ()

    use
    image = ProcessedImageField(upload_to='your/path', 
    processors=[ResizeToFit(800, 600)],
    format='JPEG', options={'quality': 70})


    In this example, the image will be inscribed in an 800x600 rectangle, keeping the proportions. Other options are not hard to guess.
    Caroline Allison

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!