DEV Community

Discussion on: Django inline formsets with Class-based views and crispy forms

Collapse
 
iaminarush profile image
iaminarush • Edited

Hey thanks a ton for this tutorial, im still quite new to django so I was wondering how would I go about adding a validation so at least one CollectionTitle is required for each Collection, thanks alot!

Collapse
 
iaminarush profile image
iaminarush

So I've figured out how to add validation for the CollectionTitle, but im doing it through views.py. Wondering if anybody knows how to add the validation to client side instead of going through views, thanks.

How I am doing it at the moment is adding a min_num and validate_min to the inlineformset_factory.

forms.py

CollectionTitleFormSet = inlineformset_factory(
    Collection, CollectionTitle, form=CollectionTitleForm,
    fields=['name', 'language'], can_delete=True, min_num=1, validate_min=True, extra=0
    )

And by setting an else function in the form_valid. I save the object after validating titles since my project requires at least one title for each collection.

views.py

class CollectionCreate(CreateView):
#kept rest the same till form_valid

def form_valid(self, form):
        context = self.get_context_data()
        titles = context['titles']
        with transaction.atomic():
            form.instance.created_by = self.request.user
            if titles.is_valid():
                self.object = form.save()
                titles.instance = self.object
                titles.save()
            else:
                context.update({'titles': titles})
                return self.render_to_response(context)
        return super(CollectionCreate, self).form_valid(form)
Collapse
 
ramialloush profile image
Rami Alloush • Edited

Great code! have been looking all day :/
This works for me

    def form_valid(self, form):
        context = self.get_context_data()
        subunits = context['subunits']
        with transaction.atomic():
            if subunits.is_valid():
                self.object = form.save()
                subunits.instance = self.object
                subunits.save()
                return super(UnitCreateView, self).form_valid(form)
            else:
                return self.render_to_response(self.get_context_data(form=form))