Django.fun

How to provide initial data to ForeignKey in ModelFormSet?

So I have this thing.

enter image description here

These are the relationships of my models

To define an event you have a Place, a QR Link and an ImageAlbum which have up to five Images.

An event may or may not have a Place

An event MUST have the main image which is marked by the main attr in the Image Form.

All the forms are in the same page, they all are processed with a single Submit

Now my troubles begin and end in the Forms Department, i have several Model Forms:

#FORMS FILE

class EventForm(ModelForm):
    date_time_start = forms.DateTimeField(input_formats=["%Y-%m-%d"],  required=True, widget=forms.DateTimeInput(format="%Y-%m-%d", attrs={"id": "cal_start", "placeholder": "yyyy-mm-dd"}))
    has_place = forms.BooleanField()

    class Meta:
        model = Event
        fields = ['title', 'subtitle', 'phrase', 'date_time_start', 'prices', 'has_place']
    
class BaseImageFormSet(BaseModelFormSet):
        
    def clean_main(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) 
            
class PlaceForm(ModelForm):
    class Meta:
        model = EventPlace
        exclude = ['uuid', 'event'] 

class QRForm(ModelForm):
    
    class Meta:
        model = EventQR
        exclude = ['uuid', 'event']

My headache is with the Images, I have to make a ModelFormSet of Images but I have to create first the album which connects the images to the event.

Here are my views:

#VIEWS FILE

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')
        event_form = EventForm(prefix='event')
        place_form = PlaceForm(prefix='place')
        qr_form = QRForm(prefix='qr')
        context = {'forms': {'Evento': event_form, 'Lugar': place_form,
                             'QR Links': qr_form}, 'image_formset': image_formset, }
        return render(request, "events/events_add.html", context)

    def post(self, request):
        event_form = EventForm(request.POST, prefix='event')
        if event_form.is_valid():
            new_event = event_form.save(commit=False)
            if event_form.cleaned_data['has_place']:
                place_form = PlaceForm(request.POST, prefix='place')
                if place_form.is_valid():
                    qr_form = QRForm(request.POST, prefix='qr')
                    if qr_form.is_valid():
                        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():
                            event_form.save()
                            new_album.save()
                            new_place = place_form.save(commit=False)
                            new_place.event = new_event
                            new_qr = qr_form.save(commit=False)
                            new_qr.event = new_event

                            new_place.save()
                            new_qr.save()
                            image_formset.save()

                            return HttpResponse('Ok', content_type='text')
                        else:
                            return Response(image_formset.errors, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        return Response(qr_form.errors, status=status.HTTP_400_BAD_REQUEST)
                else:
                    return Response(place_form.errors, status=status.HTTP_400_BAD_REQUEST)
            else:
                qr_form = QRForm(request.POST, prefix='qr')
                if qr_form.is_valid():
                    new_album = EventAlbum(event=new_event)

                    ImageFormSet = modelformset_factory(
                        EventImage, extra=5, max_num=5, formset=BaseImageFormSet)
                    image_formset = ImageFormSet(
                        request.POST, request.FILES, prefix='images')
                    if image_formset.is_valid():
                        event_form.save()
                        new_album.save()
                        image_formset.save()
                        qr_form.save()
                        return HttpResponse('Ok', content_type='text')
                    else:
                        return Response(image_formset.errors, status=status.HTTP_400_BAD_REQUEST)
                else:
                    return Response(qr_form.errors, status=status.HTTP_400_BAD_REQUEST)

        return Response(event_form.errors, status=status.HTTP_400_BAD_REQUEST) 

How would you do about saving the images?

And the whole event with its dependencies.

Please help i am stuck by now

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 →