Django.fun

Why does my ModelFormSet keeps updating the same record instead of creating a new one?

I have these Models, this is all part of an app that registers events which have images through an ImageAlbum:

class EventAlbum(models.Model):
    uuid = models.UUIDField(
        primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='eventos') 
    
    def get_main_image(self):
        return self.images.get(main=True)

class EventImage(models.Model):
    uuid = models.UUIDField(
        primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    image = models.FileField('imagen', upload_to=upload_path)
    main = models.BooleanField('principal', default=False)
    album = models.ForeignKey(EventAlbum, related_name = 'images', on_delete=models.CASCADE)

And this FormSet for the Images:

class BaseImageFormSet(BaseModelFormSet):
        
    def clean(self):
        """Checks that there is only one main image"""
        if any(self.errors):
            return
        boolean_arr = []
        for form in self.forms:
            if self.can_delete and self._should_delete_form(form):
                continue
            main_data = form.cleaned_data.get('main')
            main = main_data if main_data is not None else False
            if sum(boolean_arr) > 1:
                raise ValidationError('There can only be one main image.')
            boolean_arr.append(main) 

Here is in my Views:

class NewEventView(BaseView):
    def get(self, request, *args):
        ImageFormSet = modelformset_factory(
                            EventImage, fields=('image', 'main'),
                            extra=5, max_num=5, formset= BaseImageFormSet)
        image_formset = ImageFormSet(prefix='images')
        
        context = {'forms': {'image_formset': image_formset, }
        return render(request, "events/events_add.html", context)

    def post(self, request):
        new_album = EventAlbum(event=new_event)

        ImageFormSet = modelformset_factory(
            EventImage, fields=('image', 'main'),
            extra=5, max_num=5, formset= BaseImageFormSet)
        image_formset = ImageFormSet(request.POST, request.FILES,
                                    prefix='images')

        if image_formset.is_valid():
        
            new_album.save()
            images = image_formset.save(commit = False)
            for image in images:
                image.album = new_album
                image.save()
            image_formset.save()

            return HttpResponse('Ok', content_type='text')
        else:
            return Response((image_formset.errors, image_formset.non_form_errors()),
                        status=status.HTTP_400_BAD_REQUEST)

The thing is that the ImageFormSet keeps updating the same records instead of creating new ones. Why?

How can I change this, could it be the template?

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →