[Answered ]-Django Integrity Error Handling

2πŸ‘

βœ…

In your UserForm you can overwrite clean method of your number attribute, lets say that your attribute is called β€˜numberβ€˜

class UserForm(ModelForm):
    #your user form attributes and stuff


    def clean_number(self, value):
        user_number = value
        number_occurrences = User.objects.filter(number=user_number).count()
        if  number_occurrences > 0:
            raise forms.ValidationError("You number is already taken by other user")

        return self.cleaned_data

Check django docs about form validation

If you dont wan’t to overwrite clean method and do it whitin your view. you can. (Is not elegant)

def form(request):
    #This is using regular Django forms
    #print request.POST
    #form = EmailForm(request.POST or None)

    #This is using model forms
    number = request.POST.get('telephone')
    number_occurrences = User.objects.filter(number=user_number).count()
    if  number_occurrences > 0:
        context = {'error':'Number already exist'}
        return render(request,template,context)

    form = UserForm(request.POST or None)
    if form.is_valid():
        new_instance = form.save(commit=True)

        new_instance.save()
        context = {"form": form }
        template = "form.html"
        return render(request,template,context)
πŸ‘€levi

0πŸ‘

Before you create an object, query the db for the existence of that phone number.

if form.is_valid():
    ph_number = #"Phone number from form"
    if User.objects.filter(phone_number = ph_number).first():
        return HttpResponse("The number already exists.")
    new_instance = form.save(commit=True)
    new_instance.save()

The first() method returns the index 0 of the queryset. So, if there is element 0 in the queryset, the error message will be displayed to the user.

0πŸ‘

you can probably do something with field validation, although I donΒ΄t know exactly what your error is, or how the model is designed.
Anyway, you could try to look up whether the value is unique (i.e., look if another record exists with the same number), before trying to save it; this might be the cleanest.
https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-a-specific-field-attribute

so something like:

def clean_telephone(self):
    n = User.objects.filter(telephone=self.cleaned_data['telephone']).count()
    if n > 0:
        raise forms.ValidationError("telephone number is already in database")
    return data 

Or you could try to save it and catch the unique error with a try/except clause. This uses less databases access attempts.

πŸ‘€Frido Emans

Leave a comment