Display error message of field with unique equal True

I have a field with “unique=True” in my model this is good. The error toast message has displayed successfully . When I pass (form.as_text()) to the toast message, it returns with tow messages
The first one is (“Vendor with this Name already exists.”)
And the second says (“This field is required”)
The 2 messages appear as toast message next to each other.

if request.is_ajax() and request.method == "POST":
        form = VendorsForm(request.POST or None, request.FILES or None)
        [print('FORM-ERRORS: ', f.name, f.errors,) for f in form]
        if form.is_valid():
                save_form = form.save(commit=False)
                save_form.user = request.user
                save_form.updated_user = request.user
                name = request.POST.get("name")
               # match = Vendor.objects.filter(name=name).exists()          
                ven_name = save_form.name
                ven_id = save_form.id
                # messages.success(request, f"Vendor ({name}) created successfully.")
                # return redirect(reverse("vendors:edit_vendor", args=(id,)))
                msg = 'Vendor (%s) created successfully' % ven_name
                data['error'] = msg
                data['type'] = 'success'
                data['vendor_id'] = ven_id
                return JsonResponse(data)

            name = request.POST.get("name")
                'VALIDITY-IS: ', form.is_valid(), 
                'VENDOR-NAME: ', name, 
                'GET_JSON_DATA: ', (form.get_json_data()),  

            er = form.errors.as_json(escape_html=True)
            # error_name = er["name"]

            msg = (form.errors.as_text())
            data['error'] = msg
            data['type'] = 'error'
            data['vendor_id'] = None

            return JsonResponse(data)
        form = VendorsForm()

Why does the message appear twice ?
I have tried many things but I failed .

First, request.is_ajax() is deprecated. It’s going to go away soon.

Second, I think you’re losing information in that you’re losing the reference to the fields to which the error messages apply by display this using the as_text method on the errors. The output of your print statement would be more useful here. You’re most likely getting two errors because you have two separate errors in your form.

Third, if name is a field in the VendorsForm, then you don’t need to use this:

You can access that field directly from the form.

Which brings us to the final point - it would be helpful to see VendorsForm and the model to which it refers.

1 Like

Thanks @KenWhitesell

I found the duplicated message in another file.
Due to existing of many files I found that I have the same ajax call for “vendor form submission”,
That’s the cause of duplicated message .