Home > Software design >  Django Form with validation state for unique
Django Form with validation state for unique

Time:09-27

I try to add a validation state like "this already exist." (like registration form, see picture) just under my form input.

enter image description here

But when I submit my form i'v this error 'UNIQUE constraint failed'

this is my code

model

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

forms

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

view

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")

template

{% 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>

Thanks a lot

CodePudding user response:

you have to add errors_messages to your email field like this:

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