When you run a Django project using runserver
, Django loads the URL patterns. Usually, inside your URL patterns you import your views. Which in turn import your models and forms.
So if any of these files contains a syntax error or a python error at the top level (see below), this will cause loading the URLs to fail. However, if you scroll up your trace, you should see another error, the actual error that caused the imports to fail. It will say somewhere "during handling of this exception another exception occurred".
However, python is not actually running all the code it imports. A class definition will just cause python to read the class name and its attributes (a method is also an attribute).
When python imports a class, it calls its __new__()
method, not its __init__()
method or any other method you define. So only errors at the top level of the class (e.g. using unknown variables in the definition of attributes) or errors inside the Meta
class will be thrown.
** edit **: fields = ['some_field']
inside the Meta
class is indeed run when the class object is created (__new__()
method) and Django will check if the field exists in the corresponding model, because it assigns it to the class's _meta
attribute.
In other cases, when you say "whenever I make a mistake in my code" that should generally not raise an error because python should not be actually instantiating the form (running its __init__()
method) or running any of the methods you write. So you should avoid instantiating any classes at the top level of your code, instantiation should happen inside of functions/methods, then python won't hit these errors.
So check your views.py files to see if you are just importing form classes (from my_forms import MyForm
) or if you are also instantiating a form at the top level of your file (form = MyForm()
, note the parenthesis) or as an attribute of a class-based view.