Looking for a good example usage of get_or _create in Django views and raising a Form error
Posted
by Rik Wade
on Stack Overflow
See other posts from Stack Overflow
or by Rik Wade
Published on 2010-04-13T10:25:45Z
Indexed on
2010/04/13
11:02 UTC
Read the original article
Hit count: 448
I am looking for a good example of how to achieve the following:
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.
© Stack Overflow or respective owner