Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django Error (EXTERNAL IP)

Tags:

python

url

django

I am receiving notifications every time, when enter an address that does not exist.

Traceback (most recent call last): File "/home/user/opt/local/django/core/handlers/base.py", line 100, in get_response File "/web/blog/views.py", line 33, in post File "/home/user/local/django/db/models/manager.py", line 132, in get File "/home/user/opt/local/django/db/models/query.py", line 347, in get DoesNotExist: Post matching query does not exist.

how to solve it

like image 594
santiago Avatar asked Oct 28 '25 13:10

santiago


2 Answers

Modify your query to use get_object_or_404, or catch the YourModel.DoesNotExist (3rd paragraph) exception when you're doing the lookup, and raise a Http404 exception. When you don't catch the DoesNotExist exception the view raises a 500 error. As a side effect, this sends an exception email to the the ADMINS defined it settings.py.

Example of both cases:

from django.shortcuts import get_object_or_404

post_id = 1
post = get_object_or_404(Post, id=post_id)

# or catch the exception and do something with it

from django.http import Http404
try:
    post = Post.objects.get(id=post_id)
except Post.DoesNotExist:
    # id doesnt exist... do extra things here
    raise Http404
like image 175
Sam Dolan Avatar answered Oct 30 '25 02:10

Sam Dolan


The error was generated because your get query had failed to match any record. If you want to throw a 404 page in such an event, then sdolan has already provided with you advice on how to do that. However, if you would like to assume some sensible defaults in the event that the query fails to fetch any matching records, you could wrap the call to get around a try and catch block. For example:

try:
    post = Post.object.get(pk=id)
except Post.DoesNotExist:
    post = None
    # Probably use some sensible defaults, or do something else
like image 44
ayaz Avatar answered Oct 30 '25 03:10

ayaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!