【问题标题】:Unique=True in Django model gives IntergretyError instead of ValidationErrorDjango 模型中的 Unique=True 给出了 IntergretyError 而不是 ValidationError
【发布时间】:2019-04-23 06:27:18
【问题描述】:

我想在我的 html 表单中显示一条验证消息,例如“此电子邮件已在使用中”。

但我想我错过了一些东西。我在我的电子邮件字段中不断收到 IntegrityError。如果我在模型中使用 unique=True ,Django 不应该验证这一点并给出 ValidationError 吗?还是我必须自己尝试捕获 IntegrityError?

或者,也许可以向我展示在表单/模型中验证唯一用户的最佳实践。

models.py

class Customer(models.Model):
    FirstName = models.CharField(max_length=50)
    LastName = models.CharField(max_length=50)
    Email = models.CharField(max_length=50, unique=True, error_messages={'unique':"This email is already in use"})

views.py

def customerform(request):
if request.method == 'POST':
    form = CustomerForm(request.POST)
    if form.is_valid():
        post = Customer()
        post.FirstName = form.cleaned_data['FirstName']
        post.LastName = form.cleaned_data['LastName']
        post.Email = form.cleaned_data['Email']
        post.save()
        return render(request, 'results.html', {
        'FirstName': form.cleaned_data['FirstName'],
        'Email': form.cleaned_data['Email'],})
else:        
    form = CustomerForm()
return render(request, 'form.html', {'form':form})

forms.py

class CustomerForm(forms.Form):
    FirstName   = forms.CharField (label='First name:', max_length=50)
    LastName    = forms.CharField (label='Last name:', max_length=50)
    Email       = forms.EmailField(label='Email:', max_length=50)

form.html

<form action="/customer/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

【问题讨论】:

  • 我不确定它是否会如你所愿,但这看起来应该真的继承自 forms.ModelForm
  • 您的表单似乎没有clean_Email() 方法。这将是一个很好的起点。

标签: python django sqlite


【解决方案1】:

如果你想让表单验证自动使用模型属性,你必须使用ModelForm

class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = ["FirstName", "LastName", "Email"]

如果您想使用普通的Form,您需要手动进行验证。

【讨论】:

  • 非常感谢!!这正是我一直在寻找的。像魅力一样工作!
【解决方案2】:
def customerform(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            # first we check if email is valid
            customer = Customer.objects.filter(Email = form.cleaned_data['Email'])
            if customer.count() == 0: # email not in use
                post = Customer()
                post.FirstName = form.cleaned_data['FirstName']
                post.LastName = form.cleaned_data['LastName']
                post.Email = form.cleaned_data['Email']
                post.save()
                return render(request, 'results.html', {
                    'FirstName': form.cleaned_data['FirstName'],
                     'Email': form.cleaned_data['Email'],})
            else: # email in use so we redirect to html and we add an error message
                render(request, 'form.html', {'form':form,'error','This email is already in use'})
        else:        
            form = CustomerForm()
    return render(request, 'form.html', {'form':form})


<form action="/customer/" method="post">
    {% if error %}
        <b> {{ error }} </b> <br>
    {% endif %}
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form> 

【讨论】:

    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多