饮冰三年-人工智能-Python-29瀑布流
生活随笔
收集整理的這篇文章主要介紹了
饮冰三年-人工智能-Python-29瀑布流
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
多適用于:整版以圖片為主,大小不一的圖片按照一定的規律排列的網頁布局。
1:創建model類,并生成數據表?
from django.db import models# Create your models here. # 圖片表 class Img(models.Model):url=models.FileField(max_length=32,verbose_name="圖片路徑",upload_to='static/upload')title=models.CharField(max_length=16,verbose_name='標題')summary=models.CharField(max_length=128,verbose_name='簡介')class Meta:verbose_name_plural='圖片'def __str__(self):return self.title model2:注冊到django后臺管理頁面中,并創建管理員
from django.contrib import admin from app01 import models # Register your models here. admin.site.register(models.Img) admin.py3:添加對應的文件夾,修改settings配置,準備數據
""" Django settings for WaterfallFlow project.Generated by 'django-admin startproject' using Django 2.1.5.For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p5)q997@c#&(xtv79l24+(u-%3z$=ozv4_khe4$sz)$z$f=8cx'# SECURITY WARNING: don't run with debug turned on in production! DEBUG = TrueALLOWED_HOSTS = []# Application definition INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','app01.apps.App01Config', ]MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware', ]ROOT_URLCONF = 'WaterfallFlow.urls'TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','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',],},}, ]WSGI_APPLICATION = 'WaterfallFlow.wsgi.application'# Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': os.path.join(BASE_DIR, 'db.sqlite3'),} }# Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',},{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',},{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',}, ]# Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'), ) Setting.py?
?4:url配置
"""WaterfallFlow URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import url from django.urls import path from app01.ImgTest import ImgViewurlpatterns = [# path('admin/', admin.site.urls),url(r'^admin/', admin.site.urls),url(r'^img1.html$',ImgView.img1),url(r'^getImgs$', ImgView.getImgs),] url配置5:View設置
from django.shortcuts import render from django.http import JsonResponse from app01.models import Img# Create your views here. def img1(request):return render(request,"ImgTest/img1.html")def getImgs(request):nid = request.GET.get('nid')img_list = Img.objects.filter(id__gt=nid).values('id','url','title')img_list=list(img_list)print(img_list)ret = {'status':True,'data':img_list}return JsonResponse(ret) Views6:html 頁面
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="/static/js/jquery-3.3.1.min.js"></script><style>.w {width: 1000px;margin: 0px;}.item {width: 25%;float: left;}.item img {width: 100%;}</style> </head> <body> <div class="w" id="container"><div class="item">11</div><div class="item">22</div><div class="item">33</div><div class="item">44</div></div> <script>$(function(){initImg();})var nd=0;function initImg() {$.ajax({url:'getImgs',type:"GET",data:{nid:nd},datatype:'json',success:function(arg){var img_list=arg.data;$.each(img_list,function(index,v){var eqv=index%4;var tag = document.createElement("img");tag.src='/'+v.url;$("#container").children().eq(eqv).append(tag)})}})} </script> </body> </html> img1.html?以上這種方法有個弊端是:一次獲取所有的數據庫數據。完善:只完善部分數據,當滾輪滾到頁面最下方的時候再次請求數據獲取數據。
from django.shortcuts import render from django.http import JsonResponse from app01.models import Img from django.db.models import Q# Create your views here. def img1(request):return render(request,"ImgTest/img1.html")def getImgs(request):nid = request.GET.get('nid')nid2=int(nid)+10img_list = Img.objects.filter(Q(id__gt=nid)&Q(id__lt=nid2)).values('id','url')img_list=list(img_list)print(img_list)ret = {'status':True,'data':img_list}return JsonResponse(ret) view <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="/static/js/jquery-3.3.1.min.js"></script><style>.w {width: 1000px;margin: 0px;}.item {width: 25%;float: left;}.item img {width: 100%;}</style> </head> <body> <div class="w" id="container"><div class="item">11</div><div class="item">22</div><div class="item">33</div><div class="item">44</div></div> <script>$(function () {initImg();scrollEvent();})var nd = 0;function initImg() {$.ajax({url: 'getImgs',type: "GET",data: {nid: nd},datatype: 'json',success: function (arg) {var img_list = arg.data;$.each(img_list, function (index, v) {var eqv = index % 4;var tag = document.createElement("img");tag.src = '/' + v.url;$("#container").children().eq(eqv).append(tag)//當循環到最后一個圖片時,將圖片的id賦值給ndif(index+1==img_list.length){nd=v.id;}})}})}{#當滾輪滾動到底部時,執行initImg()#} function scrollEvent() {$(window).scroll(function () {//什么時候表示滾動到底部{#文檔高度= 窗口高度+滾動條高度#}var docHeight=$(document).height();//文檔高度var winHeight=$(window).height();//窗口高度var scrHeight = $(window).scrollTop();//滾動條高度if (winHeight+scrHeight==docHeight){console.log(1)initImg();}})}</script> </body> </html> html以上這種方法還有瑕疵,就是:定義了公共屬性nd,我們可以把公共屬性nd封裝到對象中
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="/static/js/jquery-3.3.1.min.js"></script><style>.w {width: 1000px;margin: 0px;}.item {width: 25%;float: left;}.item img {width: 100%;}</style> </head> <body> <div class="w" id="container"><div class="item">11</div><div class="item">22</div><div class="item">33</div><div class="item">44</div></div> <script>$(function () {var obj = new ScrollImg();obj.initImg();obj.scrollEvent();})function ScrollImg() {{#為了去掉全局變量,創建一個新類#}this.id = 0;this.initImg = function () {var that = this;$.ajax({url: 'getImgs',type: "GET",data: {nid: that.id},datatype: 'json',success: function (arg) {var img_list = arg.data;$.each(img_list, function (index, v) {var eqv = index % 4;var tag = document.createElement("img");tag.src = '/' + v.url;$("#container").children().eq(eqv).append(tag)//當循環到最后一個圖片時,將圖片的id賦值給ndif (index + 1 == img_list.length) {that.id = v.id;}})}})}this.scrollEvent = function () {{#當滾輪滾動到底部時,執行initImg()#}var that = this;$(window).scroll(function () {//什么時候表示滾動到底部{#文檔高度= 窗口高度+滾動條高度#}var docHeight = $(document).height();//文檔高度var winHeight = $(window).height();//窗口高度var scrHeight = $(window).scrollTop();//滾動條高度if (winHeight + scrHeight == docHeight) {console.log(1)that.initImg();}})}}</script> </body> </html> html?
轉載于:https://www.cnblogs.com/YK2012/p/10353232.html
總結
以上是生活随笔為你收集整理的饮冰三年-人工智能-Python-29瀑布流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 终极解密输入网址按回车到底发生了什么
- 下一篇: 彻夜怒肝!SpringBoot+Sent