[Answered ]-Django CreateView with form_class not creating model

2đź‘Ť

âś…

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.

class FlavorForm(forms.ModelForm):

    def clean_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 and not value.startswith('Tasty'):
            msg = 'Must start with Tasty'
            raise ValidationError(msg):
        return title

    class Meta:
        model = Flavor
        fields = ['title', 'slug', 'scoops_remaining']
👤Risadinha

Leave a comment