jaki jest właściwy sposób na sprawdzenie, czy obiekt istnieje w widoku django bez zwracania 404?
Zasadniczo wystarczy sprawdzić, czy obiekt istnieje i zwrócić obiekt. następnie na podstawie tego wykonać działania. Zastanawiam się, jak to zrobić, nie zwracając 404?
try:
listing = RealEstateListing.objects.get(slug_url = slug)
except:
listing = None
if listing:
67
3 answers
Nie użyłbym opakowania 404, gdybyś nie dostał 404. To nadużycie intencji. Po prostu złap Nie-Nie-Nie-Nie-Nie-Nie-Nie-Nie-Nie-Nie.
try:
listing = RealEstateListing.objects.get(slug_url=slug)
except RealEstateListing.DoesNotExist:
listing = None
93
Author: ironfroggy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-12 19:24:12
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-12 19:24:12
Możesz również zrobić
if not RealEstateListing.objects.filter(slug_url=slug).exists():
do stuff...
Czasami bardziej jasne jest użycie try: except: block, A innym razem istnieje metoda one-liner (), która sprawia, że kod wygląda jaśniej... wszystko zależy od logiki aplikacji.
148
Author: zzart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-05 12:31:12
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-05 12:31:12
listing = RealEstateListing.objects.filter(slug_url=slug).first()
4
Author: Henrik Heino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-12 13:06:18
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-12 13:06:18