CodeSsscala
CodeSsscala

Reputation: 749

Django Integrity Error Handling

I have created a website for user registration with first name, last name, phone no and so on. I have successfully established a connection to MySQL database. I want help regarding IntegrityError handling in django,since I'm a newbie. When 2 users input same phone number, django takes me to its debug page with whole lots of information. Instead I want to notify the user then and there that another user with same phone number already exists. Please provide any pointers on this. Following is my views.py file in which I process the form:

from django.shortcuts import render
from formProcessing.forms import UserForm




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

#This is using model forms
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)

Upvotes: 1

Views: 3259

Answers (3)

levi
levi

Reputation: 22697

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)

Upvotes: 2

Frido Emans
Frido Emans

Reputation: 5578

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.

Upvotes: 0

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

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.

Upvotes: 0

Related Questions