Using Swiper JS in Django Templates

A Comprehensive Guide for Using Swiper Components in Django Templates
November 24, 2024 by
Using Swiper JS in Django Templates
Hamed Mohammadi
| No comments yet

Incorporating an interactive and responsive carousel or slider into your Django project can enhance the user experience. Swiper JS is a modern, lightweight, and feature-rich JavaScript library perfect for implementing such functionalities. This guide will show you how to integrate Swiper JS into Django templates effectively.

Step 1: Install Swiper JS

Swiper JS can be included in your project via a Content Delivery Network (CDN) or by installing it locally. The easiest way to get started is using the CDN.

Add the following CDN links to your base template (base.html) within the <head> section for the styles and before the closing <body> tag for the scripts:

<!-- Swiper CSS -->
<link
  rel="stylesheet"
  href="https://unpkg.com/swiper/swiper-bundle.min.css"
/>

<!-- Swiper JS -->
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>

Step 2: Create a Django View and Template

Let’s assume you want to display a list of images in the slider. First, create a view that retrieves the images from your database.

models.py:

from django.db import models

class Image(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.title

views.py:

from django.shortcuts import render
from .models import Image

def image_slider(request):
    images = Image.objects.all()
    return render(request, 'slider.html', {'images': images})

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('slider/', views.image_slider, name='image_slider'),
]

Step 3: Design the Swiper Slider in the Template

Now, create the slider.html template. Use Swiper's basic structure to display the images dynamically.

slider.html:

{% extends "base.html" %}

{% block content %}
<div class="swiper-container">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    {% for image in images %}
    <div class="swiper-slide">
      <img src="{{ image.image.url }}" alt="{{ image.title }}" style="width: 100%; height: auto;">
    </div>
    {% endfor %}
  </div>
  <!-- If you want pagination -->
  <div class="swiper-pagination"></div>
  <!-- If you want navigation buttons -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
</div>

<!-- Initialize Swiper -->
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const swiper = new Swiper(".swiper-container", {
      loop: true, // Enable looping
      autoplay: {
        delay: 3000,
        disableOnInteraction: false,
      },
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  });
</script>
{% endblock %}


Step 4: Add Media Files for Images

Ensure that your project is set up to serve media files during development. In settings.py, add:

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

Update your urls.py to serve media files in development:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 5: Upload and Test

  1. Use Django’s admin panel or a custom form to upload images.
  2. Visit /slider/ in your browser to see the Swiper slider in action.

Customizing Swiper

Swiper JS offers extensive customization options, such as:

  • Adding Effects:
    effect: "fade",
    fadeEffect: {
      crossFade: true,
    },
    
  • Responsive Breakpoints:
    breakpoints: {
      640: {
        slidesPerView: 1,
      },
      1024: {
        slidesPerView: 2,
      },
    },
    

Modify the swiper initialization script in the template to include these options.

Conclusion

Integrating Swiper JS with Django templates is straightforward and provides powerful features to create modern, responsive sliders. By dynamically rendering content from your database, you can keep your UI fresh and engaging without hardcoding elements.

Ready to give your website a visual upgrade? Try Swiper JS today!

Using Swiper JS in Django Templates
Hamed Mohammadi November 24, 2024
Share this post
Tags
Archive

Please visit our blog at:

https://zehabsd.com/blog

A platform for Flash Stories:

https://readflashy.com

A platform for Persian Literature Lovers:

https://sarayesokhan.com

Sign in to leave a comment