在goods应用下的
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form class="form-inline" method="post" enctype="">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">请输入账号</label>
<input type="text" class="form-control" id="exampleInputEmail3" name="uname">
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">请输入密码</label>
<input type="password" class="form-control" name="pwd" id="exampleInputPassword3" >
</div>
<button type="submit" class="btn btn-default">登陆</button>
</form>
<a href="/goods/downw">下载图片</a>
</body>
</html>
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
欢迎您:{{ request.session.get("k1",None) }}
<form action="/goods/upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
选择文件:<input type="file" name="myfile"><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('/addgoods', views.addgoods),
path('/upload', views.upload),
path('/downw', views.down),
]
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.conf import settings
import os
# Create your views here.
def index(request):
if request.method=="POST":
uname=request.POST.get("uname")
pwd = request.POST.get("pwd")
if uname=="admin" and pwd=="123":
request.session["k1"]=uname
return redirect("/goods/upload")
#视图函数返回的类型是HttpResponse或是他的子类
return render(request,"index1.html")
def addgoods(request):
return render(request,"addgoods.html")
def upload(request):
print(request.session.get("k1",None))
if request.method=="POST":
myfile=request.FILES.get("myfile")#获取上传的文件
# myfile.name#文件的名字
# myfile.file文件的内容 BytesIO
path=os.path.join(settings.BASE_DIR,"goods/files/"+myfile.name)#拼接路径以及文件名
fileio=open(path,"wb")#利用open打开一个新文件
fileio.write(myfile.file.read())#写入文件内容
fileio.close()
return HttpResponse("上传成功")
return render(request,"upload.html")
def down(request):
#得到图片文件
file=open("goods/static/211010113337-4.jpg","rb")
#创建httpresponse对象,把图片作为对象的响应内容
response=HttpResponse(file)
#响应内容的类型
response["Content-Type"]="application/octet-stream"
#如何处理响应内容--以附件形式下载,并指明文件名
response["Content-Disposition"]="application;filename=211010113337-4.jpg"
return response
settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^9u)66i)&n7^mhmhncpsj@#w1-%cc%^h@7l!mve7c#_^-40+k9'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'goods',
'books'
]
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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, "books/templates"), os.path.join(BASE_DIR, "goods/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',
],
'environment': 'mysite.jinja2_env.environment'
},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.2/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.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # session保存的引擎 SESSION_CACHE_ALIAS = 'default' # 使用的缓存别名(默认内存缓存,也可以是memcache),此处 别名依赖缓存的设置
SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即: sessionid=随机字符串
SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径
SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名
SESSION_COOKIE_SECURE = False # 是否Https传输cookie
SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输
SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期
SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存