Good example usage of get_or _create in Django views and raising a Form error
- by Rik Wade
I would like to use get_or_create to check whether an object already exists in my database. If it does not, then it will be created. If it does exist, then I will not create the new object, but need to raise a form error to inform the user that they need to enter different data (for example, a different username).
The view contains:
p, created = Person.objects.get_or_create(
email = registration_form.cleaned_data['email'],
defaults = {
'creationDate': datetime.datetime.now(),
'dateOfBirth': datetime.date(1970,1,1)
})
So 'p' will contain the existing Person if it exists, or the new Person if not. I would like to act on the boolean value in 'created' in order to skip over saving the Person and re-display the registration_form and raise an appropriate form validation error.
The alternative I'm considering is doing a check in a custom Form validation method to see whether a Person exists with the data in the provided 'email' field, and just raising a validation error.