Django part: 2

Photo by Faisal on Unsplash

Django part: 2

Pass Data From Django View to Template

To pass data from a Django view to a template, you can use the render() function along with a dictionary containing the data you want to pass.

  1. Define your view function:

     from django.shortcuts import render
    
     def my_view(request):
         data = {
             'message': 'Hello, world!',
             'items': ['apple', 'banana', 'orange']
         }
         return render(request, 'my_template.html', data)
    
  2. Access the data in the template:

    In your template (my_template.html), you can access the data using template variables.

     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>My Template</title>
     </head>
     <body>
         <h1>{{ message }}</h1>
         <ul>
             {% for item in items %}
                 <li>{{ item }}</li>
             {% endfor %}
         </ul>
     </body>
     </html>
    

Using Django Template for Loop

#view function
from django.shortcuts import render

def my_view(request):
    my_list = ['apple', 'banana', 'orange']
    return render(request, 'my_template.html', {'my_list': my_list})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Template</title>
</head>
<body>
    <h1>Fruits</h1>
    <ul>
        {% for fruit in my_list %}
            <li>{{ fruit }}</li>
        {% endfor %}
    </ul>
</body>
</html>

{% for fruit in my_list %} iterates over each element in the my_list and {% endfor %} marks the end of the loop. Within the loop, {{ fruit }} displays each item in the list

If Else Statement in Django Template

use the {% if %} and {% else %} template tags to conditionally display different content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Authentication Status</title>
</head>
<body>
    {% if user_authenticated %}
        <h1>Welcome, {{ request.user.username }}!</h1>
        <p>You are logged in.</p>
    {% else %}
        <h1>Welcome, Guest!</h1>
        <p>You are not logged in. Please <a href="{% url 'login' %}">log in</a>.</p>
    {% endif %}
</body>
</html>

In this example:

  • If the user is authenticated (user_authenticated is True), it will display a welcome message with the username and a message indicating that the user is logged in.

  • If the user is not authenticated (user_authenticated is False), it will display a generic welcome message for guests and provide a link to the login page.

set up the static directory

  1. Create a static directory:

     myproject/
     ├── myapp/
     │   ├── migrations/
     │   ├── templates/
     │   └── ...
     ├── static/  <-- Create this directory
     └── ...
    
  2. Configure STATICFILES_DIRS setting: In your Django settings file (settings.py), configure the STATICFILES_DIRS setting to include the path to the static directory you created. This tells Django where to find your static files during development

     # settings.py
    
     STATICFILES_DIRS = [
         BASE_DIR / "static",
     ]
    
  3. Load static files in templates: In your HTML templates, load static files using the {% load static %} template tag and reference the static files using the {% static %} template tag.

     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>My Website</title>
         <link rel="stylesheet" href="{% static 'css/style.css' %}">
     </head>
     <body>
         <img src="{% static 'images/logo.png' %}" alt="Logo">
         <script src="{% static 'js/script.js' %}"></script>
     </body>
     </html>
    

Tags of Django | use Extends and Include Django Template Tags

To create a fixed header and footer in a Django HTML template using the {% include %} template tag.

  1. Create Header and Footer HTML files:

     <header>
         <h1>This is the header</h1>
         <!-- Add navigation links, logo, etc. -->
     </header>
    
     <footer>
         <p>&copy; 2024 My Website. All rights reserved.</p>
         <!-- Add footer content such as contact information, social media links, etc. -->
     </footer>
    
  2. Include Header and Footer in the Base Template: Create a base HTML template that will serve as the main template for your website layout. Use the {% include %} template tag to include the header and footer HTML files.

    base.html:

     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>{% block title %}My Website{% endblock %}</title>
         <!-- Add CSS links, meta tags, etc. -->
     </head>
     <body>
         {% include 'header.html' %}
    
         <main>
             {% block content %}
             <!-- Content of the specific page goes here -->
             {% endblock %}
         </main>
    
         {% include 'footer.html' %}
     </body>
     </html>
    
  3. Extend Base Template in Other Templates: In your other templates, extend the base template (base.html) and override the {% block content %} with the specific content for each page.

    home.html (example):

     {% extends 'base.html' %}
    
     {% block title %}Home | My Website{% endblock %}
    
     {% block content %}
     <h2>Welcome to the home page!</h2>
     <!-- Add home page content here -->
     {% endblock %}
    

URL Template Tags in Django and How to Use It

In Django, URL template tags are used to generate URLs for views within your Django project. They provide a way to create dynamic URLs in your HTML templates without hardcoding them, allowing for more flexible and maintainable code. The two main URL template tags in Django are {% url %} and {% static %}

  1. Defining URL patterns:

     # urls.py
     from django.urls import path
     from . import views
    
     urlpatterns = [
         path('home/', views.home, name='home'),
         path('about/', views.about, name='about'),
         # Other URL patterns...
     ]
    
  2. Using URL template tags in templates:

     <a href="{% url 'about' %}">About Us</a>
     <img src="{% static 'images/logo.png' %}" alt="Logo">