SoFunction
Updated on 2024-11-19

Django waterfall implementation examples

demand analysis

Now is the era of "picture is king", in browsing some websites, often see similar to this screen is full of pictures. Pictures of different sizes, but arranged in space, this is a waterfall layout.

  • Layout as a waterfall to get images out of the database
  • Take an equal number (7) of images at a time, and load them into the page.
  • Automatically reloads the image when the slider scrolls to the very bottom

Realization process

  • Managing models in packages
  • Automatically upload images to static files static
  • Front-end page with four images per line (four divs)
  • When the page loads, it automatically sends a request to the backend in the form of ajax to get the image data, and then loops through js to generate img tags to add to each div.
  • JS loop image information list, the current loop element index and the number of images in each row (4) to find the remainder, and then use the remainder to locate each div tag.

modeling

Here, I manage the model as a packagemodelsPreparationapp/models/video/img_models.py

from  import models


class Img():
    """
    upload_to: address of the uploaded file
    """
    src = (max_length=64, verbose_name='Image address', upload_to='app/static/app/upload')
    title = (max_length=64, verbose_name='Title')
    summary = (max_length=128, verbose_name='Introduction')

    class Meta:
        verbose_name_plural = 'Pictures'

    def __str__(self):
        return 

view function

compileapp/

from  import render
from  import JsonResponse
from .img_models import Img


def img(request):

    return render(request, 'app/')


def getImgs(request):
    nid = ('nid')
    print(nid)

    # nid is 0 for the first time, and 7 entries for each time.
    last_position_id = int(nid) + 7
    postion_id = str(last_position_id)

    # Get data for 0 < id < 7
    img_list = (id__gt=nid, id__lt=postion_id).values('id', 'title', 'src')
    img_list = list(img_list)   # Convert dictionary format to list form
    ret = {
        'status': True,
        'data': img_list
    }

    return JsonResponse(ret)

Take out the eligible data in the backend and package it into theJSON format data, the front-end template is then passedjQuery Generate it in a loopimg tag and add it to thediv Tagged in.

(architecture) formwork

compileapp/templates/app/

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>waterfalls</title>
    <style type="text/css">
        .box1{
            width: 1000px;
            margin: 0 auto;
        }

        .box1 .item{
            width: 25%;
            float: left;
        }

        .item img{
            width: 100%;
        }
    </style>
</head>
<body>
    <h1>waterfalls</h1>
    <div class="box1" >
        <div class="item">

        </div>

        <div class="item">

        </div>

        <div class="item">

        </div>

        <div class="item">

        </div>
    </div>


    <script src="{% static 'app/jquery/jquery-3.1.' %}"></script>
    <script>
        $(function () {
            initImg();
            scroll();
        });

        NID = 0;
        LASTPOSTION = 3;    // Loop over the last position.
        function initImg() {
            $.ajax({
                url: '/app/getImgs/',
                type: 'GET',
                data: {nid: NID},
                dataType: 'JSON',
                success: function (arg) {
                    if (){
                       var img_list = ;
                       $.each(img_list, function (index, value) {
                          var n = (index + LASTPOSTION + 1) % 4;
{# (n); // 0, 1, 2, 3 always 0, 1, 2, 3#}
                          var img = ('img');
                           = '/' + ;    //  app/static/app/upload/

                           // That is, add img tags to the first, second, third, and fourth divs, with eq(0) being the first one.
                          $('#container').children().eq(n).append(img);
                          if (index + 1 == img_list.length){
                              (n, );
                              LASTPOSTION = n;
{#                              NID = ;#}
                          }
                       });
                    }
                }
            })
        }

        // Listen to the pulleys
        $(window).scroll(function () {
            // Document height
            var doc_height = $(document).height();
            // Window height
            var window_height = $(window).height();
            // Pulley height
            var scroll_height = $(window).scrollTop();
            if (window_height + scroll_height == doc_height){
                initImg();
            }
        })

        
    </script>
</body>
</html>

settings Configuration

TEMPLATES = [
    {
        'BACKEND': '',

        # templates settings
        'DIRS': [(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                '.context_processors.debug',
                '.context_processors.request',
                '.context_processors.auth',
                '.context_processors.messages',
            ],
        },
    },
]

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

# Added /app because it allows the template to find images in static.
STATIC_URL = '/app/static/'
STATICFILES_DIRS = (
    (BASE_DIR, 'app', 'static'),
)


TEMPLATE_DIRS = ((BASE_DIR, 'app', 'templates'),)

urlconf configuration

This is mine.app/

# Project/
from  import admin
from  import path, include

urlpatterns = [
    path('admin/', ),
    path('app/', include('')),
]

# app/
from  import path
from app import views

urlpatterns = [
    path('img/', , name='img'),
    path('getImgs/', , name='getImgs'),
]

package management model

The modeling part of the whole project is managed in the form of packages, and some functional parts are designed in separate model files, so the corresponding models are imported in the package file.

compileapp/models/video/__init__.py

from .img_models import Img

Encapsulating Global Variables with Objects

up topJS In the code, we use global variables, the actual development should try to avoid the use of global variables, here with the object to encapsulate it.

// Global variable encapsulation
$(function () {
    var obj = new ScrollImg();   // Define an object
    ();         
    ();
});

// Object ScrollImg
function ScrollImg() {
    // Encapsulate the previous global variables inside the object so that only its internals can use them.
     = 0;       
     = 3;

    // Send an ajax request to the backend to get the image information.
     = function () {
        var that = this;
        $.ajax({
            url: '/app/getImgs/',
            type: 'GET',
            data: {nid: },
            dataType: 'JSON',
            success: function (arg) {
                var img_list = ;
                $.each(img_list, function (index, value) {
                    var n = (index +  + 1) % 4;
                    var img = ('img');
                     = '/' + ;

                    $('#container').children().eq(n).append(img);
                    if (index + 1 == img_list.length) {
                         = n;

                        // After each fetch, assign the id of the last one to the NID and pass it to the backend, which then fetches 7 pieces of data based on this condition.
                         = ;
                    }
                });
            }
        })
    };

     = function () {
        var that = this;

        // listen to the pulley, when the pulley height + window height == document height, that is, the pulley has slid to the bottom, and then execute fetchImg() function, and then take out the data from the database
        $(window).scroll(function () {
            var scroll_height = $(window).scrollTop();
            var window_height = $(window).height();
            var doc_height = $(document).height();
            if (scroll_height + window_height == doc_height ) {
                ();
            }
        })
    }
}

This is the approximate distribution of the entire program:

Reference Blog

Small feature waterfall implementation

django implementation of waterfall, combined search, ladder comments, captcha

to this article on the realization of the Django waterfall example of the article is introduced to this , more related Django waterfall content please search my previous posts or continue to browse the following related articles I hope that you will support me in the future !