Ana is learning

Learning Django part 2

January 28, 2019

Django

Backstory: I’ve always been terrified of backend and saw it as something mystical and way over my head. But I’ve decided that it’s time to face the beast and start diving into it. This is my journal on learning Django (along with Python where I have just some basic knowledge). You can check the part 1 first.

After we installed Django, the files created are the following:

  1. __init__.py is an empty file that instructs Python to treat this directory as a Python package. This prevents directories with a common name, such as string, datetime, from unintentionally hiding valid modules that occur later on the module search path. For example, if we have the files

    • mydirectory/example/__init__.py
    • mydirectory/example/module.py

and mydirectory is on our path, we can import the code in module.py as import spam.module or from spam import module. If we remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

Leaving an __init__.py file empty is considered normal and even a good practice, if the package’s modules and sub-packages do not need to share any code.

  1. settings.py is a core file in Django projects. Some important notes about it are these:

    • we have to turn the DEBUG to False when we send the app into production
    • the default value for ALLOWED_HOSTS is [](an empty list). When DEGUB = False, we will have to also add some domains, otherwise we’ll get a Bad Request error. This prevents HTTP Host header attacks.
    • SECRET_KEY is another security variable that is randomly generated to each new project started.
  1. urls.py defines the site url-to-view mappings. A URLconf is like a table of contents for our Django project. It’s a mapping between URLs and the view functions that should be called for those URLs.

  2. wsgi.py is used to help our Django application communicate with the web server. WSGI (Web Server Gateway Interface) specifies the rules which need to be implemented by the Web Application side and the Web Server side so that they can interact with each other.

For more information, check the following: MDN - Django tutorial, Django Book, Django docs.


Ana Filote

Ana Filote Self-taught front-end developer. Trying to learn new things.