Email validation in form

36 views
Skip to first unread message

Moreplavec

unread,
Sep 12, 2017, 7:52:37 AM9/12/17
to Django users
Greetings,

i have strange problem with my model form. I have simple form for taking orders, model looks like:

class Order(models.Model):
    name = models.CharField(max_length=50, blank=False, verbose_name='Jméno')
    surname = models.CharField(max_length=50, blank=False, verbose_name='Příjmení')
    email = models.EmailField(max_length=254, blank=True)
    phone = models.CharField(max_length=50, verbose_name='Telefon', blank=True)
    coursedate = models.ForeignKey(CourseDate, verbose_name='Termín')
    note = models.CharField(max_length=500, blank=True, verbose_name='Poznámka')
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    def __str__(self):
        return '%s, %s' % (self.surname, self.coursedate.course.name)

and template (bootstrap, modal):

 
{{ form.non_field_errors }}
<form action="." method="POST">{% csrf_token %}
                        {{ form.non_field_errors }}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                        {% for field in form.visible_fields %}
                        <div class="form-group">
                            {% if field.field.required %}
                            {{ field.errors }}
                                {{ field.label }}<span class="special_class">*</span>{{ field }}
                            {% else  %}
                                {{ field.label }} {{ field }}
                            {% endif %}
                        </div>
                        {% endfor %}
                    
                    </div>
                    <div class="modal-footer">
                        <a href="#" data-dismiss="modal">Close</a>
                        <button type="submit" class="btn btn-primary">Send</button>
                    </div>
                    </form> 

And in model:

def serve(self, request):
        from crm.forms import OrderFormNew
        if request.method == 'POST':
            form = OrderFormNew(request.POST)
            if form.is_valid():
                form.date_changed = datetime.date.today()
                form.save()
                return render(request, 'courses/course_web.html', {
                    'page': self,
                    'form': form,
                })
        else:
            form = OrderFormNew()
            form.fields["coursedate"].queryset = CourseDate.objects.filter(course=self.course).order_by('date_start')
        return render(request, 'courses/course_web.html', {
            'page': self,
            'form': form,
        })

 
All fields work fine, but when i insert email, for example "asdf@asdf" form is taken away but not saved to model. So Django wont validate, but form takes it. How to make form to use same rules as Django? When i use email "te...@test.com" all works fine and data are in model saved.

Thanks for help, maybe it's to much things together while using pop-up + validation and i'm mixing things together and error is shown somewhere, but lost in code :)

Moreplavec

Vijay Khemlani

unread,
Sep 12, 2017, 10:47:16 AM9/12/17
to django...@googlegroups.com
"asdf@asdf" is not a valid email so form.is_valid returns False and form.save is never called



--
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...@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/fabad5ea-8535-483c-895f-ebb0d90e5c1a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Moreplavec

unread,
Sep 12, 2017, 11:10:29 AM9/12/17
to Django users
I understand, but why while using model form it's not cought by form itself same as missing or incorect field like "asdf" for email? This is my problem. I need to show error and not to try to save :)



Dne úterý 12. září 2017 12:47:16 UTC+2 Vijay Khemlani napsal(a):
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Vijay Khemlani

unread,
Sep 12, 2017, 12:23:38 PM9/12/17
to django...@googlegroups.com
If you render the form using the typical methods ("{{ form.as_p }}" or similar) then there should be a message over the email field with the error.

From the code, you an use form.errors to check the errors in the form.

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...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Daniel Roseman

unread,
Sep 12, 2017, 1:18:29 PM9/12/17
to Django users
On Tuesday, 12 September 2017 08:52:37 UTC+1, Moreplavec wrote:
<snip>

<form action="." method="POST">{% csrf_token %}
                        {{ form.non_field_errors }}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                        {% for field in form.visible_fields %}
                        <div class="form-group">
                            {% if field.field.required %}
                            {{ field.errors }}
                                {{ field.label }}<span class="special_class">*</span>{{ field }}
                            {% else  %}
                                {{ field.label }} {{ field }}
                            {% endif %}
                        </div>
                        {% endfor %}

<snip>

For some reason, you only show `{{ form.errors }}` if the field is required; and your email is not (becase you have blank=True in the model for that field). 

Move the form.errors element out of that if block.
--
DR.

Daniel Roseman

unread,
Sep 12, 2017, 1:18:58 PM9/12/17
to Django users
Sorry, that should have been `{{ field.errors }}`. 
Message has been deleted

Moreplavec

unread,
Sep 13, 2017, 9:03:32 AM9/13/17
to Django users
Thanks. I made it as needed and wrote simple JS to call popup if there is an error to rise modal again after reload.

Thanks!

Dne úterý 12. září 2017 15:18:58 UTC+2 Daniel Roseman napsal(a):

Melvyn Sopacua

unread,
Sep 13, 2017, 9:09:37 AM9/13/17
to django...@googlegroups.com
First, make sure the field is rendered as an input tag with type
"email". If it's not, your Django version is out of date or you're
overriding the widget somewhere.
Second, read this:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation

The standard pattern isn't good enough as it doesn't require a dot in
the domain part.
This is why browser form validation succeeds and Django's fails.
Django could maybe propagate the validator
pattern to the "pattern" attribute of the input tag, but I'm not sure
that even works given various
browser differences in regex implementation.

The following css snippet, would allow you to test the pattern should
you decide to provide one yourself via widget attributes:

input[type='email']:invalid { color: red }


On Tue, Sep 12, 2017 at 5:23 PM, Moreplavec <stanisl...@gmail.com> wrote:
> I have {{ field.errors }} im my template. I changed model to not contain
> blank=True, but problem is still the same.
>
>
> Dne úterý 12. září 2017 15:18:58 UTC+2 Daniel Roseman napsal(a):
>>
>>
> --
> 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...@googlegroups.com.
> To post to this group, send email to django...@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/14a999b0-7bfc-4f5c-9215-b739e1ebf5e9%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.



--
Melvyn Sopacua
Reply all
Reply to author
Forward
0 new messages