Beginners' Guide: Variables and Loop Syntax in Django Template Engine Jinja2

This article introduces the core syntax of variables and loops in the Django template engine Jinja2. The template engine combines backend data with HTML templates to generate web pages. As Django's default engine, Jinja2 is the focus here, with emphasis on variables and loops. Variable syntax: Variables are enclosed in double curly braces {{}}. They support strings, numbers, booleans, and lists (displayed directly). Dictionaries can be accessed using dot notation (.) or square brackets ([]), such as {{ user.name }} or {{ user["address"]["city"] }}. Note that undefined variables will cause errors, and variables in templates are not modifiable. Loop syntax: Use {% for variable in list %} to iterate. It is accompanied by forloop.counter (for counting), first/last (for marking the first and last elements), and {% empty %} to handle empty lists. Examples include looping through lists or lists of dictionaries (e.g., each dictionary in a user list). Summary: Mastering variables and loops enables quick data rendering. Subsequent articles will cover advanced topics such as conditions and filters.

Read More
Django from Scratch: Build a Simple Blog System with ORM and Template Engine in 3 Steps

This article introduces how to quickly build a blog system displaying article lists using Django, with a core understanding of ORM operations for data and template rendering for pages. Step 1: Environment preparation and project initialization. After installing Django, create the project `myblog` and the app `blog`. The project structure includes configuration directories, app directories, and command-line tools. Step 2: Define data models using ORM. Write a `Post` class (with fields: title, content, publication time) in `blog/models.py`, which is automatically mapped to a database table. Activate the model (configure `settings.py`) and execute migrations to generate the table. Step 3: Views and template rendering. Write a view function in `views.py` to retrieve article data and configure routing to distribute requests. Render the article list in the template `index.html` using Django template syntax, supporting loops and variable output. Running `python manage.py runserver` allows access to the blog. The core is to master Django's ORM model definition, view processing, and template rendering processes, with potential for subsequent feature expansion.

Read More