如何使用django显示无效电子邮件地址的错误消息

时间:2016-03-12 17:40:19

标签: python django forms email emailfield

我在用户输入时显示错误消息时遇到问题 无效的邮件地址。

这是我的forms.py文件:

from django.db import models
from django import forms
from django.core.validators import EmailValidator

# Create your models here.
class Contact(models.Model):
    name = models.CharField(max_length = 50)
    email = models.EmailField(blank = False, max_length = 200)
    message = models.TextField(blank = False)

这是我的models.py文件

from django.shortcuts import render, redirect, render_to_response
from django.http import HttpResponseRedirect

from .models import Contact
from .forms import ContactForm
from django.contrib import messages

# Create your views here.

def contact_create(request):
    form = ContactForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit = False)
        instance.save()
        form = ContactForm()
        messages.success(request, 'Your message was sent successfully. We will contact you shortly.')
        return HttpResponseRedirect('/home/#contact')

    context = {
        "form": form,
    }

    return render(request, 'index.html', context)

这是我的views.py文件:

{% include "messages_display.html" %}
<form method="POST" action="">
    {% csrf_token %}
    <div class="row half">

        <div class = "6u" > {{ form.name }} </div>
        <div class = "6u" > {{ form.email }} </div>

    </div>
    <div class="row half">
        <div class="12u"> {{ form.message }} </div>
    </div>
    <div class="row">
        <div class="12u">
            <ul class="actions">
                <input type="submit" class="button" value="Send Message" />
            </ul>
        </div>
    </div>
</form>

最后我的表单在index.html文件中

class Foo
{
    public Foo(int value)
    {
        this.Value = value;
    }
    public int Value { get; private set; }        
}

所以,message.success显示正常,没有问题,我想,如果用户输入无效的电子邮件地址,在电子邮件字段下显示错误消息,就像名称字段或消息字段留空,它显示&#34;请填写此字段&#34;。

谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

当名称或消息字段为空时,您的表单不会显示错误,原因与它没有显示无效的电子邮件错误相同:因为您没有在模板中放置任何内容显示那些错误。你需要添加{{ form.email.errors }}等来实现它。

答案 1 :(得分:1)

要显示邮件字段的错误消息,您的表单的电子邮件字段应为forms.EmailInput

因此,您的forms.py文件应为:

from django import forms
from .models import Contact
from django.db import models


class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = [
            'name',
            'email',
            'message',
        ]

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget = forms.TextInput(attrs={
            'placeholder': 'Name', 
            'required': True})

        self.fields['email'].widget = forms.EmailInput(attrs={
            'placeholder': 'Email',
            'required': True})

        self.fields['message'].widget = forms.Textarea(attrs={
            'placeholder': 'Message',
            'rows': 6,
            'required': True})