... options ) def from_string ( self , template_code ): try : return Template ( self . engine . from_string ( template_code )) except foobar . TemplateCompilationFailed as exc : raise TemplateSyntaxError ( exc . args ) def get_template ( self , template_na ... me ): try : return Template ( self . engine . get_template ( template_name )) except foobar . TemplateNotFound as exc : raise TemplateDoesNotExist ( exc . args , backend = self ) except foobar . TemplateComp ... ... ango's default). do_stuff () with transaction . atomic (): # This code executes inside a transaction. do_more_stuff () try/except ブロック内で atomic をラップすると、integrity error を自然な形で処理できます: from django.db import IntegrityError , trans ... nsaction . atomic def viewfunc ( request ): create_parent () try : with transaction . atomic (): generate_relationships () except IntegrityError : handle_exception () add_children () この例では、 generate_relationships() が整合性制約を破ってデータベース ... create_parent() での変更はそのまま同じトランザクションにバインドされます。 generate_relationships() 内での試行は、 handle_exception() が呼び出された時点ですでに安全にロールバックされていることに留意してください。したがって、必要に応じてデータベース上で ... ... gross violations. Remember that PEP 8 is only a guide, so respect the style of the surrounding code as a primary goal. An exception to PEP 8 is our rules on line lengths. We allow up to 88 characters in code, as this is the line length used by black . ... tests, use assertRaisesMessage() and assertWarnsMessage() instead of assertRaises() and assertWarns() so you can check the exception or warning message. Use assertRaisesRegex() and assertWarnsRegex() only if you need regular expression matching. Use as ... rts in these groups: future, standard library, third-party libraries, other Django components, local Django component, try/excepts. Sort lines in each group alphabetically by the full module name. Place all import module statements before from module i ... ... il has been configured but avoid raising an error if it hasn't (e.g., in a reusable library), wrap the send call in try: / except mail.MailerDoesNotExist: pass . To ignore all exceptions (e.g., to avoid cascading failures in an error handler that sends ... mail), wrap the send call in try: / except Exception: pass . To ignore only SMTP-related errors, wrap the send call in try / except OSError: pass . Note that this ig ... fail_silently specifically to ignore those errors, consider instead intercepting SMTPRecipientsRefused and/or SMTPResponseException s with particular smtp_code values as a more precise filter.) To create an email configuration that ignores certain bac ... ... を初期化する アプリケーション読み込みプロセス が完了する前にモデルを使用しようとしたときに発生します。 ObjectDoesNotExist exception ObjectDoesNotExist [ソース] Model.DoesNotExist 例外の基底クラスです。 ObjectDoesNotExist のための try/except は、すべて ... のモデルの DoesNotExist 例外をキャッチします。 get() を参照してください。 ObjectNotUpdated New in Django 6.0. exception ObjectNotUpdated [ソース] The base class for Model.NotUpdated exceptions. A try/except for ObjectNotUpdated will catch ... NotUpdated exceptions for all models. save() を参照してください。 EmptyResultSet exception EmptyResultSet [ソース] EmptyResultSet は、クエリ ... ... qs1 . intersection ( qs2 , qs3 ) 制限については union() を参照してください。 difference() difference ( * other_qs ) SQL の EXCEPT 演算子を使用して、 QuerySet には存在するが、他の QuerySet には存在しない要素のみを保持します。例: >>> qs1 . difference ( q ... ncluding an argument from an aggregation (e.g. using the result of annotate() ) doesn't make sense: doing so will raise an exception. The aggregated values will always be fetched into the resulting queryset. 注釈 The defer() method (and its cousin, onl ... その結果、連続して only() を呼び出すと、最後に指定したフィールドだけが考慮されることになります: # This will defer all fields except the headline. Entry . objects . only ( "body" , "rating" ) . only ( "headline" ) defer() は段階的に(遅延読み込みリストにフ ... ... 登録します: @register . filter ( expects_localtime = True ) def businesshours ( value ): try : return 9 <= value . hour < 17 except AttributeError : return "" このフラグがセットされていると、フィルタの最初の引数がタイムゾーンを意識した datetime である場合 ... token ): try : # split_contents() knows not to split quoted strings. tag_name , format_string = token . split_contents () except ValueError : raise template . TemplateSyntaxError ( " %r tag requires a single argument" % token . contents . split ()[ 0 ... 数は構文エラーに対して django.template.TemplateSyntaxError を親切なメッセージとともに発生させます。 The TemplateSyntaxError exceptions use the tag_name variable. Don't hardcode the tag's name in your error messages, because that couples the tag's name t ... ... iew). Using the former pattern was straightforward since the form can guess from the context (i.e. which method raised the exception) where the errors belong and automatically process them. This remains the canonical way of adding errors when possible. ... is True . This allows template origins to be inspected and logged outside of the django.template infrastructure. TypeError exceptions are no longer silenced when raised during the rendering of a template. The following functions now accept a dirs param ... the beginning of your script with: >>> import django >>> django . setup () Otherwise, you will hit an AppRegistryNotReady exception. WSGI scripts Until Django 1.3, the recommended way to create a WSGI application was: import django.core.handlers.wsgi ... ... _string , str ): stream_or_string = stream_or_string . splitlines () try : objects = csv . DictReader ( stream_or_string ) except Exception as exc : raise DeserializationError () from exc super () . __init__ ( objects , ** options ) def _handle_object ... ame : obj [ field . name ] for field in model_fields if field . name in obj } yield from super () . _handle_object ( obj ) except ( GeneratorExit , DeserializationError ): raise except Exception as exc : raise DeserializationError ( f "Error deserializ ... ... fields (for example: timestamps) that were auto-populated by a save() now need explicit values in any fixture. 設定 Better exceptions The old EnvironmentError has split into an ImportError when Django fails to find the settings module and a RuntimeErro ... . If you always want a slash on such URLs, rewrite the pattern as: r "/some_prefix/(.*/)$" Smaller model changes Different exception from get() Managers now return a MultipleObjectsReturned exception instead of AssertionError : Old (0.96): try : Model ... . objects . get ( ... ) except AssertionError : handle_the_error () New (1.0): try : Model . objects . get ( ... ) except Model . MultipleObjectsReturned ... 2026年10月08日