具有唯一性验证状态的 Django 表单

Django Form with validation state for unique

我尝试添加一个验证状态,例如“这已经存在”。 (像注册表,看图片)就在我的表单输入下面。

但是当我提交我的表格时我遇到了这个错误'UNIQUE constraint failed'

这是我的代码

型号

class Company(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    siret = models.CharField(max_length=50, unique=True)

表格

class CheckoutForm(forms.Form):
    siret = forms.CharField(required=True,  widget=forms.TextInput(attrs={'placeholder': 'Ton SIRET'}))
    class Meta:
        model = Company
        fields = ('siret')

    def clean(self):
        siret = cleaned_data.get('siret')
        if siret:
            raise forms.ValidationError("This siret exist.")
        else:
            return siret

查看

def post(self, request, *args, **kwargs):
    form = CheckoutForm(self.request.POST)
    if form.is_valid():
        siret = form.cleaned_data.get('siret')
        company = Company(
            user = self.request.user,
            siret = siret,
        )
        company.save()
        context = {
        'company': company,
        }
        
        return redirect("core:payment")
    else:
        messages.info(self.request, "Please fill in the shipping form properly")
    return redirect("core:checkout")

模板

{% load crispy_forms_tags %}
<main>
    <div class="container wow fadeIn">
        <h2 class="my-5 h2 text-left">Checkout form</h2>
        <div class="row">
            <div class="col-md-8 mb-4">
                <div class="card">

                    <form method="post" class="card-body">
                        {% csrf_token %}
                        {{ form|crispy }}
                        <button class="btn btn-primary" id="checkout-button" data-secret="{{ session_id }}">
                            Checkout
                        </button>
                    </form>
                </div>
            </div>

非常感谢

您必须像这样将 errors_messages 添加到您的电子邮件字段:

    email = models.EmailField(
    _('email address'),
    blank=True,
    unique=True,
    null=True,
    error_messages={
        'unique': _("A user with that email address already exists."),
    }
)