Sunday, January 29, 2017

form_invalid

I need get data from a form when submit is clicked even if data are invalid, inconplete or empty.
I try to override form_invalid in CreateView but it is never called and form_valid, obviously, only if data are valid.
Why form_invalid is never called?

I have this test project with django 1.10.5 and python 3.5

models.py

class Demo(models.Model):
        demo_descr = models.CharField("Description",
            max_length=50,
        )
        demo_code = models.CharField("Code",
            max_length=5,
        )

        def __str__(self):
                return self.demo_descr
   
        class Meta:
            verbose_name = "Test"
            verbose_name_plural = "Tests"
            ordering = ["demo_descr"]

views.py

class DemoForm(forms.ModelForm):
    class Meta:
        model = models.Demo
        fields = ('demo_descr','demo_code')
  

class DemoCreateView(CreateView):
    form_class = DemoForm
    success_url = 'demo'
    template_name = 'test_form.html'
    model = models.Demo

    def form_valid(self, form):
        print('valid')
        return CreateView.form_valid(self, form)

    def form_invalid(self, form):
        print('invalid')
        return CreateView.form_invalid(self, form)

urls.py

url(r'^demo$', views.DemoCreateView.as_view(),  name='demo'),


test_form.html

<form method="post" action="">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save" />
</form>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c4ab5b85-13cc-4569-aa0d-5ef4dd6911a4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment