Reputation: 1148
I need to check if an object exists in a table. If the object doesn't exist I want to save it, if it does exist I want to refresh the page and tell the user that the identifier (quote number) already exists. I have this example code:
def some_method(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid:
quote = request.POST.get('quote')
if SomeModel.objects.get(quote_number = quote).exists():
refresh with error #not sure how to do
else:
save object #I can do this part
The problem I am running into is that when I check if the object exists (and it does) then the code will raise an error saying the object doesn't exist before it hits the if
. Which means on the webpage is full of coding information rather than the refresh with a message for the user.
I want to be able to have a little pop up message or something for the user to enter a new quote number rather than having the developer error page show up.
Am I going about this the correct way?
Upvotes: 1
Views: 7901
Reputation: 168
You can use get_or_create
. It returns a tuple with object retrieved (or created) and a boolean value. If boolean value is True
when it's a new object, and if it's False
when object already exists and you can throw desired error.
Upvotes: 0
Reputation: 2088
I would do something like this:
from django.http import HttpResponseRedirect
from django.contrib import messages
...
try:
some_object = SomeModel.objects.get(quote_number=quote)
message.warning(request, 'some message')
return HttpResponseRedirect('some-url')
except SomeModel.DoesNotExist:
some_object = SomeModel.objects.create(quote_number=quote)
...
And in the template you can display the message just like so:
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
Upvotes: 2
Reputation: 78546
The problem is get
returns an object, but exists
only works with querysets. A Model.DoesNotExist
error will be raised when you use get
and the object does not exist.
You should use filter
instead of get
:
qs = SomeModel.objects.filter(quote_number = quote)
if qs.exists():
...
else:
...
Upvotes: 4