G
G
galahard12022-03-12 22:43:50
Django
galahard1, 2022-03-12 22:43:50

How to edit via MultiFileField form?

Several photos are attached to one post through a separate model and MultiFileFieldfield, the essence of the problem is that I cannot understand and find in the search engine how can I display already uploaded photos in the MultiFileField when editing through the form?
Perhaps there are some better ways to upload multiple photos to a post with further editing options in the form?

models

class Photo(models.Model):
    image = models.ImageField(upload_to='institutions/ads')
    ads = models.ForeignKey(AdsModel, related_name='photos', on_delete=models.CASCADE)

class AdsModel(models.Model):
    title = models.CharField(max_length=100, verbose_name='Заголовок объявления')
    slug = models.SlugField(unique=True)
    category = models.ForeignKey(CategoriesAds, on_delete=models.PROTECT, verbose_name='Категория', related_name='category_ads')
    content = models.TextField()
....

form
class AddAdsForm(ModelForm):
    photos = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True,
                                                                     }), required=False)

    class Meta:
        model = AdsModel
        fields = ['title', 'category', 'content', 'photo', 'phone', 'price']


view
class AddAdsView(FormView):
    form_class = AddAdsForm
    template_name = 'institutions/add_ads.html'
    success_url = '/' 

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        photos = request.FILES.getlist('photos')
        if form.is_valid():
            id = form.save().pk
            ads = AdsModel.objects.get(pk=id)
            if photos:
                for f in photos:
                    fl = Photo(ads=ads, image = f)
                    fl.save()
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question