Django入门,制作在线相册管理
在線相冊管理
- 步驟
- 創建項目
- 配置settings文件
- 構建模型
- 創建templates目錄,創建靜態頁面
- 配置路由
- 定義view文件
- 啟動項目
- gitee源碼地址:
步驟
注意:運行代碼要確保系統安裝了MySQLdb驅動
創建項目
cmd終端運行以下命令,創建一個名為MyPhoto的項目
django-admin startproject MyPhoto #MyPhotox項目名稱切換到MyPhoto目錄下
cd MyPhoto運行目錄下的manage.py文件,創建Photoapp
python manage.py startapp Photoapp并在MyPhoto目錄下創建static和templates文件夾;然后在static文件夾創建pics文件夾,templates文件夾創建Photoapp文件夾(注意:與Photoapp同目錄哦。)
配置settings文件
打開MyPhoto/settings.py文件進行配置
from pathlib import Path import os# Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'du78ncc8w!1=(3b2+ob)*)1_w0lrk!d@#yc=3^hcq6#5y8-p6j'# SECURITY WARNING: don't run with debug turned on in production! DEBUG = TrueALLOWED_HOSTS = ['*'] #測試,允許所有用戶訪問# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','Photoapp' #添加一下app ]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 = 'Myphoto.urls'TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join('templates')],#配置HTML文件夾路徑'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 = 'Myphoto.wsgi.application'# Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases #配置連接數據庫 DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'Photo',#數據庫名稱'USER':'root',#用戶'PASSWORD':'',#密碼'HOST':'localhost','PORT':3306} }# Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validatorsAUTH_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/3.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/3.1/howto/static-files/ #配置靜態文件目錄,后期圖片保存位置 STATIC_URL = '/static/'STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), )構建模型
from django.db import models from datetime import datetime # Create your models here. class Photo(models.Model):id=models.AutoField(primary_key=True,)name=models.CharField(max_length=200)img_src=models.ImageField(upload_to='./static/pics/')#將保存在/static/pics/的圖片路徑保存到數據庫addtime=models.DateTimeField(default=datetime.now)def __str__(self):return '%s:%s'%(self.name,self.addtime)class Meta:db_table="myphoto" #指定數據庫表名接著,打開cmd,j進行文件遷移,自動在名為Photo的數據庫創建一個名為myphoto的數據表
python manage.py migrate python manage.py makemigrations
創建templates目錄,創建靜態頁面
在templates目錄下創建一個Photoapp文件夾,分別創建index.html,edit.html,info.html,upload.html,menu.html
menu.html
index.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>在線相冊信息管理</title><style type="text/css">img{width: 75px;height: 75px;}</style><script>//自定義執行信息刪除提示判斷,參數uu是成功的刪除url地址function doDel(uu){if(confirm("確定要刪除嗎?")){//網頁跳轉window.location=uu;}}</script> </head> <body>{% include 'Photoapp/menu.html' %}<center><table cellspacing="0" border="1px" width="800px"><tr><th>id號</th><th>標題</th><th>添加時間</th><th>圖片</th><th>操作</th></tr>{% for photo in photolist %}<tr><td>{{photo.id}}</td><td>{{photo.name}}</td><td>{{photo.addtime|date:'Y-m-d H:i:s'}}</td><td><img src="{{photo.img_src}}"/></td><td><a href="{% url 'editusers' photo.id %}">編輯</a><a href="javascript:doDel('{% url 'delusers' photo.id %}');">刪除</a></td></tr>{% endfor %}</table></center> </body> </html>edit.html
<!DOCTYPE html> <html><head><meta charset="utf-8"/><title>用戶信息管理</title></head><body><center>{% include "Photoapp/menu.html" %}<h3>修改用戶信息</h3><form action="{% url 'updateusers' %}" method="post"><input type="hidden" name="id" value="{{photo.id}}"/>{% csrf_token %}<table width="280" border="0"><tr><td>名稱</td><td><input type="text" name="name" value="{{photo.name}}"/></td></tr> <!-- <tr>--> <!-- <td>圖片</td>--> <!-- <td><input type="text" name="age" value="{{photo.img_src}}"/></td>--> <!-- </tr>--><tr><td colspan="2" align="center"><input type="submit" value="提交"/><input type="reset" value="重置"/></td></tr></table></form></center></body> </html>info.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><center>{% include 'Photoapp/menu.html' %}<h3>{{info}}</h3></center></body> </html>upload.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>上傳圖片</title> </head> <body>{% include 'Photoapp/menu.html' %}<center><form action="{% url 'doupload' %}" method="post" enctype="multipart/form-data">{% csrf_token %}圖片名稱:<input type="text" name="name"><br/>上傳文件:<input type="file" name="img"><br/><input type="submit" value="提交"></form></center> </body> </html>配置路由
MyPhoto/urls.py
from django.contrib import admin from django.urls import path,includeurlpatterns = [path('admin/', admin.site.urls),path('',include('Photoapp.urls')) ]Photoapp/urls.py
from django.urls import path from . import viewsurlpatterns = [# path('',views.index,name='index'),path('',views.user,name='user'),path('upload/',views.upload,name='upload'),#上傳圖片path('doupload/',views.doupload,name='doupload'),path('user/<int:uid>/del', views.delUsers, name="delusers"), #執行用戶信息刪除path('user/<int:uid>/edit', views.editUsers, name="editusers"), #加載用戶信息編輯表單path('user/update/', views.updateUsers, name="updateusers"), #執行用戶信息編輯 ]定義view文件
Photoapp/views.py
import datetimefrom django.http import HttpResponse from django.shortcuts import render from Photoapp.models import Photo # from PIL import Image # import time# Create your views here. def index(request):return render(request,'Photoapp/index.html')#實例化對象 def user(request):list=Photo.objects.all()context={'photolist':list}return render(request,'Photoapp/index.html',context)#圖片上傳 def upload(request):return render(request,'Photoapp/upload.html')#處理上傳文件 def doupload(request):i=1myfile_name=request.POST.get("name",None)myfile = request.FILES.get("img",None)if not myfile:return HttpResponse("沒有上傳的文件信息")Photo.objects.create(name=myfile_name,img_src=myfile)#生成上傳后的文件名# filename = str(myfile.name.split('.')[0])+"."+myfile.name.split('.').pop()filename='LX'+str(i)+"."+myfile.name.split('.').pop()destination = open("./static/pics/"+filename,"wb+")for chunk in myfile.chunks(): #分塊讀取上傳文件內容并寫入目標文件destination.write(chunk)destination.close()# # 執行圖片縮放# im = Image.open("./static/" + filename)# # 縮放到75*75(縮放后的寬高比例不變):# im.thumbnail((75, 75))# # 把縮放后的圖像用jpeg格式保存:# im.save("./static/pics/s_" + filename, None)context = {'info': '圖片上傳成功!'}return render(request,"Photoapp/info.html",context)# return HttpResponse(myfile.name+'上傳成功!')i=i+1#執行用戶信息刪除操作 def delUsers(request,uid):try:ob = Photo.objects.get(pk=uid) #獲取要刪除用戶信息ob.delete() #執行刪除context = {'info':'刪除成功!'}except:context = {'info':'刪除失敗!'}return render(request,"Photoapp/info.html",context)#加載修改表單,準備用戶信息修改 def editUsers(request,uid):try:ob = Photo.objects.get(pk=uid) #獲取要修改的用戶信息context = {'photo':ob}return render(request,"Photoapp/edit.html",context)except:context = {'info':'沒有找到要修改的信息!'}return render(request,"Photoapp/info.html",context)# 執行信息編輯操作 def updateUsers(request):try:ob = Photo.objects.get(id= request.POST['id'])ob.name = request.POST['name']ob.save()context = {'info':'修改成功!'}return render(request,"Photoapp/info.html",context)except:context = {'info':'修改失敗!'}return render(request,"Photoapp/info.html",context)啟動項目
MyPhoto文件夾shift+鼠標右鍵打開PowerShell
打開瀏覽器,輸入http://localhost:8000/進入主頁
注意:涉及文件以及路由過多,需理清思路,不建議一次性復制,不然出bug都不知道在哪里改,文件目錄名字一定要正確
gitee源碼地址:
https://gitee.com/lx-2022/online-photo
總結
以上是生活随笔為你收集整理的Django入门,制作在线相册管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Epson 打印机设置
- 下一篇: office2016专业增强版