You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fromdjango.httpimportHttpResponse, HttpResponseNotFounddefmy_view(request):
# ... ifcondition==True:
returnHttpResponseNotFound('<h1>Page not found</h1>')
else:
returnHttpResponse('<h1>Page was found</h1>')
or
fromdjango.httpimportHttpResponsedefmy_view(request):
# ... ifcondition==True:
returnHttpResponse('<h1>Page not found</h1>', status_code='404')
else:
returnHttpResponse('<h1>Page was found</h1>')
Raise error handling (in views.py)
fromdjango.httpimportHttp404, HttpResponsefrom .modelsimportProductdefdetail(request, id):
try:
p=Product.objects.get(pk=id)
exceptProduct.DoesNotExist:
raiseHttp404("Product does not exist")
returnHttpResponse("Product Found")
Custom page error handling (in views.py)
First in settings.py set DEBUG to FALSE and add '*' to the ALLOWED_HOSTS to include all possible hosts.
#settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG=FALSEALLOWED_HOSTS= ['*']
...
Exception Classes
ObjectDoesNotExist: All the exceptions of the DoesNotExist are inherited from this base exception.
EmptyResultSet: This exception is raised if a query does not return any result.
FieldDoesNotExist: This exception is raised when the requested field does not exist.
try:
field=model._meta.get_field(field_name)
exceptFieldDoesNotExist:
returnHttpResponse("Field Does not exist")
MultipleObjectsReturned: When you expect a certain query to return only a single object, however multiple objects are returned. This is when you need to raise this exception.
PermissionDenied: This exception is raised when a user does not have permission to perform the action requested.
ViewDoesNotExist: This exception is raised by django.urls when a requested view does not exist, possibly because of incorrect mapping defined in the URLconf.
Django’s Form API
defmyview(request):
ifrequest.method=="POST":
form=MyForm(request.POST)
ifform.is_valid():
#process the form data else:
returnHttpResponse("Form submitted with invalid data")