[Django]-Using Django CreateView to handle formset – It doesnt validate

9👍

Solution

pip install django-extra-views

And in view.py:

from extra_views import FormSetView
class ItemFormSetView(ModelFormSetView):
    model = Service
    template_name = 'service_formset.html'

There’s a discussion about getting this into Django core, but the discussions seems to have stagnated.
https://code.djangoproject.com/ticket/16256

Where I found the solution

At this repository https://github.com/AndrewIngram/django-extra-views
there’s a view called ModelFormSetView, which does exactly what I needed.
It’s a class-based view, that does the same as CreateView, but for formsets.

👤james

0👍

Django go into form_invalid() and the form.errors say ‘this field is required’ for the length and name field.

This is normal and due to the required field paramatere:

By default, each Field class assumes the value is required, so if you
pass an empty value — either None or the empty string (“”) — then
clean() will raise a ValidationError exception:

If you want to inverse that, you can set required=False:

class Service(models.Model):
    TIME_CHOICES = (
        (15, '15 minutes'),
        (30, '30 minutes'),
        )
    length = models.FloatField(choices=TIME_CHOICES,max_length=6, required=False)
    name = models.CharField(max_length=40, required=False)

What am I missing to get it do validate correctly

Did you try to post a form with name and length values ?

👤jpic

Leave a comment