First of all, I was vaguely aware of error numbers such as 404 and 500, so I googled easily. http://human-dust.kdn.gr.jp/doujin/net/errormsg.html http://www.seohacks.net/blog/crawl_index/http_statuscode/
It's still named, but it uses a module called Http404. The description in the tutorial is as follows.
from django.http import Http404
# ...
def detail(request, poll_id):
try: #With the code here ...
pobject = Poll.objects.get(pk=poll_id) #What is pk?
except Poll.DoesNotExist: #When it comes to this····
raise Http404 #Treat as a 404 error
return render_to_response('polls/detail.html', {'poll': pobject}) #If there is no problem, reach here
Also, there seems to be a shortened way of writing here as well. In that case,
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
pobject = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': pobject})
Feeling like that. Is it okay to not use the try statement here? In fact, the above-mentioned one also casually uses the shortcuts that appeared last time. Personally, I don't want to use abbreviations until I understand how it works, so I dared to fix it as follows.
from django.http import Http404
#…
def detail(request,poll_id):
try:
pobject = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
temp = loader.get_template('polls/detail.html')
contxt = Context({
'poll':pobject
})
return HttpResponse(temp.render(contxt))
It's a little long, but I feel like I can catch the flow.
Well, that's fine, but it seems that DJango has prepared the essential error screen without having to create a template by yourself. I don't feel the need to make my own so far, so I'll go through it. If you want to create it, you can put it in the template directory with the file name 404.html. __ However, I didn't understand how to set it even after reading the explanation (define a variable called handler404 in URLConf?). __
Set DEBUG in setting.py to False (if True, traceback takes precedence)
Similarly, set ALLOWED_HOSTS (it seems that you can enter your own domain like ‘.example.com’, but ‘*’ is OK if you want anything)
In addition, it seems that there is not much difference in what to do even in the case of 500 (server error).
Recommended Posts