1

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

tomferrari
  • 53
  • 4
  • can it be that it fails to `save` the object because one already exists which raises the UNIQUE constraint field – JSRB Sep 20 '21 at 10:53
  • Yes but If there already already one exist in my database I’d like to redirect to the same form with a red message error like ‘this siret already exist’ just under the input like the picture. – tomferrari Sep 20 '21 at 10:57
  • so you'll have to call the clean class in your view or at what point does `clean(self)` trigger? – JSRB Sep 20 '21 at 11:10
  • yes but i don't know how to do i try but its don't work .. – tomferrari Sep 20 '21 at 11:28
  • Does `siret.clean()` in the view work? (Not sure sorry, trying to help but never built s.th. myself yet) – JSRB Sep 20 '21 at 12:03
  • see here: https://stackoverflow.com/questions/33307855/when-are-model-methods-called-in-django you need to call the Form method within your view – JSRB Sep 20 '21 at 12:29

1 Answers1

1

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."),
    }
)
EL hassane
  • 134
  • 1
  • 9
  • Thx a lot, at first I try this `def clean(self): cleaned_data = super().clean() siret = cleaned_data.get('siret') if Company.objects.filter(siret=siret).count() > 0: self.add_error('siret', 'This Siret already use')`. Its work too but you solution are more simple :) – tomferrari Sep 26 '21 at 12:18