Skip to content Skip to sidebar Skip to footer

Django Createview With Form_class Not Creating Model

I'm practicing from Two Scoops of Django book and i have a problem with form_class in CreateView. If i'm using just fields in the CreateView it's saving the model, if i'm using the

Solution 1:

Your code probably just works as expected (it looks that way):

"it's not saving and not redirecting" := that is what happens when there is a validation error.

Override form_invalid as well and print some log output. Or just output the form errors in the template.

What happens in case of validation errors in Django is that the form is reloaded and the errors are added to the template context so that they can be rendered for the user.


Just a side note:

As alternative to

self.fields['title'].validators.append(validate_tasty)

You can simply add the validate_tasty method directly to your FlavorForm under the name clean_title and clean_slug. This is a Django standard way for adding custom validation logic.

classFlavorForm(forms.ModelForm):

    defclean_title(self):
        # even if this is a required field, it might be missing# Django will check for required fields, no need to raise# that error here, but check for existence
        title = self.cleaned_data.get('title', None)
        if title andnot value.startswith('Tasty'):
            msg = 'Must start with Tasty'raise ValidationError(msg):
        return title

    classMeta:
        model = Flavor
        fields = ['title', 'slug', 'scoops_remaining']

Post a Comment for "Django Createview With Form_class Not Creating Model"