亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Django瀑布流的實現(xiàn)示例

 更新時間:2023年03月23日 09:16:44   作者:風老魔  
在瀏覽一些網(wǎng)站時,經(jīng)常會看到類似于這種滿屏都是圖片,本文主要介紹了Django瀑布流的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下

需求分析

現(xiàn)在是 "圖片為王"的時代,在瀏覽一些網(wǎng)站時,經(jīng)常會看到類似于這種滿屏都是圖片。圖片大小不一,卻按空間排列,就這是瀑布流布局。

  • 以瀑布流形式布局,從數(shù)據(jù)庫中取出圖片
  • 每次取出等量(7 條)的圖片,加載到頁面
  • 當滑輪滾動到最底端時,自動再加載圖片

實現(xiàn)流程

  • 以包形式管理模型
  • 將圖片自動上傳到靜態(tài)文件 static
  • 前端頁面每行排列四張圖片(四個 div )
  • 當頁面加載時,以 ajax 形式自動向后臺發(fā)送請求,獲取圖片數(shù)據(jù),再用 js 循環(huán)生成 img 標簽添加到每個 div 中
  • JS 循環(huán)圖片信息列表,將當前循環(huán)元素的索引與每行排列的圖片數(shù)目(4張)求余數(shù),再利用余數(shù)定位每個 div 標簽

模型設計

在這里,我以包的形式管理模型 models,編寫 app/models/video/img_models.py

from django.db import models


class Img(models.Model):
    """
    upload_to: 上傳文件地址
    """
    src = models.FileField(max_length=64, verbose_name='圖片地址', upload_to='app/static/app/upload')
    title = models.CharField(max_length=64, verbose_name='標題')
    summary = models.CharField(max_length=128, verbose_name='簡介')

    class Meta:
        verbose_name_plural = '圖片'

    def __str__(self):
        return self.title

視圖函數(shù)

編寫 app/views.py

from django.shortcuts import render
from django.http import JsonResponse
from app.models.video.img_models import Img


def img(request):

    return render(request, 'app/img.html')


def getImgs(request):
    nid = request.GET.get('nid')
    print(nid)

    # nid 第一次取為 0,每次取 7 條
    last_position_id = int(nid) + 7
    postion_id = str(last_position_id)

    # 獲取 0 < id < 7 的數(shù)據(jù)
    img_list = Img.objects.filter(id__gt=nid, id__lt=postion_id).values('id', 'title', 'src')
    img_list = list(img_list)   # 將字典格式轉(zhuǎn)換為列表形式
    ret = {
        'status': True,
        'data': img_list
    }

    return JsonResponse(ret)

在后臺取出符合條件的數(shù)據(jù),然后打包成 JSON 格式數(shù)據(jù),前端模板再通過 jQuery 將其循環(huán)生成 img 標簽,并添加到 div 標簽中。

模板

編寫 app/templates/app/img.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>瀑布流</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>瀑布流</h1>
    <div class="box1" id="container">
        <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.1.js' %}"></script>
    <script>
        $(function () {
            initImg();
            scroll();
        });

        NID = 0;
        LASTPOSTION = 3;    // 循環(huán)最后那個的位置
        function initImg() {
            $.ajax({
                url: '/app/getImgs/',
                type: 'GET',
                data: {nid: NID},
                dataType: 'JSON',
                success: function (arg) {
                    if (arg.status){
                       var img_list = arg.data;
                       $.each(img_list, function (index, value) {
                          var n = (index + LASTPOSTION + 1) % 4;
{#                          console.log(n);    // 0、1 、2 、3    一直為 0、1 、2 、3#}
                          var img = document.createElement('img');
                          img.src = '/' + value.src;    //  app/static/app/upload/7.jpg

                           // 也就是給第一、二、三、四給 div 添加 img 標簽,eq(0) 為第一個
                          $('#container').children().eq(n).append(img);
                          if (index + 1 == img_list.length){
                              console.log(n, value.id);
                              LASTPOSTION = n;
{#                              NID = value.id;#}
                          }
                       });
                    }
                }
            })
        }

        // 監(jiān)聽滑輪
        $(window).scroll(function () {
            // 文檔高度
            var doc_height = $(document).height();
            // 窗口高度
            var window_height = $(window).height();
            // 滑輪高度
            var scroll_height = $(window).scrollTop();
            if (window_height + scroll_height == doc_height){
                initImg();
            }
        })

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

settings 配置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        # templates 設置
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

# 因為讓模板能夠找到 static 中圖片,添加了 /app
STATIC_URL = '/app/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'app', 'static'),
)


TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'app', 'templates'),)

urlconf 配置

這是我的 app/urls.py

# Project/urls.py
from django.contrib import admin
from django.urls import path, include

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

# app/urls.py
from django.urls import path
from app import views

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

包管理模型

整個項目的模型部分,以包的形式管理,有些功能部分單獨設計模型文件,因此要在包文件中導入相應模型。

編寫 app/models/video/__init__.py

from app.models.video.img_models import Img

使用對象封裝全局變量

在上面 JS 代碼中,我們使用了全局變量,實際開發(fā)中應該盡量避免使用全局變量,在這里用對象將其封裝。

// 全局變量封裝
$(function () {
    var obj = new ScrollImg();   // 定義一個對象
    obj.fetchImg();         
    obj.scrollEvent();
});

// 對象 ScrollImg
function ScrollImg() {
    // 將之前的全局變量封裝在對象內(nèi)部,僅其內(nèi)部能使用
    this.NID = 0;       
    this.LASTPOSITION = 3;

    // 向后臺發(fā)送 ajax 請求,獲取圖片信息
    this.fetchImg = function () {
        var that = this;
        $.ajax({
            url: '/app/getImgs/',
            type: 'GET',
            data: {nid: that.NID},
            dataType: 'JSON',
            success: function (arg) {
                var img_list = arg.data;
                $.each(img_list, function (index, value) {
                    var n = (index + that.LASTPOSITION + 1) % 4;
                    var img = document.createElement('img');
                    img.src = '/' + value.src;

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

                        // 每取完一次,便把最后那條的 id 賦值給 NID 傳到后臺,再根據(jù)這個條件取 7 條數(shù)據(jù)
                        that.NID = value.id;
                    }
                });
            }
        })
    };

    this.scrollEvent = function () {
        var that = this;

        // 監(jiān)聽滑輪,當滑輪高度+窗口高度==文檔高度時,即表示滑輪已經(jīng)滑動到最底部,再執(zhí)行 fetchImg() 函數(shù),再從數(shù)據(jù)庫取出數(shù)據(jù)
        $(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 ) {
                that.fetchImg();
            }
        })
    }
}

這是整個項目大致分布:

參考博客

小功能瀑布流的實現(xiàn)

django實現(xiàn)瀑布流、組合搜索、階梯評論、驗證碼

到此這篇關于Django瀑布流的實現(xiàn)示例的文章就介紹到這了,更多相關Django瀑布流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關文章

  • Python數(shù)據(jù)分析之?Pandas?Dataframe修改和刪除及查詢操作

    Python數(shù)據(jù)分析之?Pandas?Dataframe修改和刪除及查詢操作

    這篇文章主要介紹了Python數(shù)據(jù)分析之?Pandas?Dataframe修改和刪除及查詢操作的相關資料,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • python雙向鏈表實現(xiàn)實例代碼

    python雙向鏈表實現(xiàn)實例代碼

    python雙向鏈表和單鏈表類似,只不過是增加了一個指向前面一個元素的指針,下面的代碼實例了python雙向鏈表的方法
    2013-11-11
  • python如何創(chuàng)建TCP服務端和客戶端

    python如何創(chuàng)建TCP服務端和客戶端

    這篇文章主要為大家詳細介紹了python如何創(chuàng)建TCP服務端和客戶端,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • Python pickle模塊常用方法代碼實例

    Python pickle模塊常用方法代碼實例

    這篇文章主要介紹了Python pickle模塊常用方法代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-10-10
  • 解決webdriver.Chrome()報錯:Message:''chromedriver'' executable needs to be in Path

    解決webdriver.Chrome()報錯:Message:''chromedriver'' executable n

    這篇文章主要介紹了解決webdriver.Chrome()報錯:Message:'chromedriver' executable needs to be in Path ,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • python在windows調(diào)用svn-pysvn的實現(xiàn)

    python在windows調(diào)用svn-pysvn的實現(xiàn)

    本文主要介紹了python在windows調(diào)用svn-pysvn的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • Python OpenCV實現(xiàn)裁剪并保存圖片

    Python OpenCV實現(xiàn)裁剪并保存圖片

    這篇文章主要為大家詳細介紹了Python OpenCV實現(xiàn)裁剪并保存圖片,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • Python圓周率算法不只是3.14更多玩法揭秘

    Python圓周率算法不只是3.14更多玩法揭秘

    本篇博客將引領讀者穿越數(shù)學、計算和可視化的領域,通過豐富的示例代碼,揭示π的獨特之處,無論是計算π的各種方法、應用領域中的角色,還是π作為無理數(shù)的特性,我們將通過Python的鏡頭,發(fā)現(xiàn)這個數(shù)字在數(shù)學世界中的非凡之處
    2024-01-01
  • Python使用redis pool的一種單例實現(xiàn)方式

    Python使用redis pool的一種單例實現(xiàn)方式

    這篇文章主要介紹了Python使用redis pool的一種單例實現(xiàn)方式,結(jié)合實例形式分析了Python操作redis模塊實現(xiàn)共享同一個連接池的相關技巧,需要的朋友可以參考下
    2016-04-04
  • PyCharm 配置遠程python解釋器和在本地修改服務器代碼

    PyCharm 配置遠程python解釋器和在本地修改服務器代碼

    這篇文章主要介紹了PyCharm 配置遠程python解釋器和在本地修改服務器代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07

最新評論