Django cascade of realization

demand analysis

Now is the "picture is king" era, when browsing some websites, often see something like this are full screen picture. Pictures of different sizes, but according to the spatial arrangement, it is this waterfall flow layout.

  • Waterfall stream in the form layout, remove the picture from the database
  • Each time the same amount taken (7) of the picture, is loaded into the page
  • When the wheel to scroll to the very bottom, and then automatically loads images

Implementation process

  • Management model pack form
  • The pictures are automatically uploaded to a static file static
  • Front page picture every four rows (four div)
  • When the page is loaded, the form is automatically sent to the background ajax request to obtain image data, and then generates a cycle js img tag was added to each of div
  • JS circular image information list, the number of the current picture index for each cycle elements arranged in rows and (4) the number of remainder, the remainder recycled locate each tag div

Model Design

Here, I am in the form of package management model models, write 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

View function

Write 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 的数据
    img_list = Img.objects.filter(id__gt=nid, id__lt=postion_id).values('id', 'title', 'src')
    img_list = list(img_list)   # 将字典格式转换为列表形式
    ret = {
        'status': True,
        'data': img_list
    }

    return JsonResponse(ret)

Remove the qualified data in the background, and then packed into a JSONformat data, then through the front end of the template jQueryto generate cyclic imgtag, and added to divthe label.

template

Write 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;    // 循环最后那个的位置
        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;#}
                          }
                       });
                    }
                }
            })
        }

        // 监听滑轮
        $(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>

Configuration 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 Configuration

This is my 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'),
]

Package Management Model

Model of the whole project, in the form of a management pack, some functional part of a separate document design model, so the model to be imported in the respective package file.

Write app/models/video/__init__.py:

from app.models.video.img_models import Img

Global variables using object encapsulation

In the above JScode, we use a global variable, the actual development of the global variables should be avoided, where it is encapsulated by the object.

// 全局变量封装
$(function () {
    var obj = new ScrollImg();   // 定义一个对象
    obj.fetchImg();         
    obj.scrollEvent();
});

// 对象 ScrollImg
function ScrollImg() {
    // 将之前的全局变量封装在对象内部,仅其内部能使用
    this.NID = 0;       
    this.LASTPOSITION = 3;

    // 向后台发送 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 传到后台,再根据这个条件取 7 条数据
                        that.NID = value.id;
                    }
                });
            }
        })
    };

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

        // 监听滑轮,当滑轮高度+窗口高度==文档高度时,即表示滑轮已经滑动到最底部,再执行 fetchImg() 函数,再从数据库取出数据
        $(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();
            }
        })
    }
}

This is a general distribution of the entire project:

Now is the "picture is king" era, when browsing some websites, often see something like this are full screen picture. Pictures of different sizes, but according to the spatial arrangement, it is this waterfall flow layout.

  • Waterfall stream in the form layout, remove the picture from the database
  • Each time the same amount taken (7) of the picture, is loaded into the page
  • When the wheel to scroll to the very bottom, and then automatically loads images

Implementation process

  • Management model pack form
  • The pictures are automatically uploaded to a static file static
  • Front page picture every four rows (four div)
  • When the page is loaded, the form is automatically sent to the background ajax request to obtain image data, and then generates a cycle js img tag was added to each of div
  • JS circular image information list, the number of the current picture index for each cycle elements arranged in rows and (4) the number of remainder, the remainder recycled locate each tag div

Model Design

Here, I am in the form of package management model models, write 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

View function

Write 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 的数据
    img_list = Img.objects.filter(id__gt=nid, id__lt=postion_id).values('id', 'title', 'src')
    img_list = list(img_list)   # 将字典格式转换为列表形式
    ret = {
        'status': True,
        'data': img_list
    }

    return JsonResponse(ret)

Remove the qualified data in the background, and then packed into a JSONformat data, then through the front end of the template jQueryto generate cyclic imgtag, and added to divthe label.

template

Write 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;    // 循环最后那个的位置
        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;#}
                          }
                       });
                    }
                }
            })
        }

        // 监听滑轮
        $(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>

Configuration 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 Configuration

This is my 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'),
]

Package Management Model

Model of the whole project, in the form of a management pack, some functional part of a separate document design model, so the model to be imported in the respective package file.

Write app/models/video/__init__.py:

from app.models.video.img_models import Img

Global variables using object encapsulation

In the above JScode, we use a global variable, the actual development of the global variables should be avoided, where it is encapsulated by the object.

// 全局变量封装
$(function () {
    var obj = new ScrollImg();   // 定义一个对象
    obj.fetchImg();         
    obj.scrollEvent();
});

// 对象 ScrollImg
function ScrollImg() {
    // 将之前的全局变量封装在对象内部,仅其内部能使用
    this.NID = 0;       
    this.LASTPOSITION = 3;

    // 向后台发送 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 传到后台,再根据这个条件取 7 条数据
                        that.NID = value.id;
                    }
                });
            }
        })
    };

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

        // 监听滑轮,当滑轮高度+窗口高度==文档高度时,即表示滑轮已经滑动到最底部,再执行 fetchImg() 函数,再从数据库取出数据
        $(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();
            }
        })
    }
}

This is a general distribution of the entire project:

Guess you like

Origin www.cnblogs.com/gaodi2345/p/11634979.html