上传图片

  • 当Django在处理文件上传的时候,文件数据被保存在request.FILES
  • FILES中的每个键为<input type="file" name="" />中的name
  • 注意:FILES只有在请求的方法为POST 且提交的<form>带有enctype="multipart/form-data" 的情况下才会包含数据。
  • 否则,FILES 将为一个空的类似于字典的对象

(1) 自定义上传的模板代码

<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <form method="post" action="upload/" enctype="multipart/form-data">
        <input type="text" name="title"><br>
        <input type="file" name="pic"/><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>
  • 自定义上传的视图代码
from django.shortcuts import render
from django.http import HttpResponse
from PIL import Image
import time,os

def upload(request):
    '''执行图片的上传'''
    myfile = request.FILES.get("mypic",None)
    if not myfile:
        return HttpResponse("没有上传文件信息")
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()

    # 执行图片缩放
    im = Image.open("./static/pics/"+filename)
    # 缩放到75*75(缩放后的宽高比例不变):
    im.thumbnail((75, 75))
    # 把缩放后的图像用jpeg格式保存: 
    im.save("./static/pics/s_"+filename,None)

    #执行图片删除
    #os.remove("./static/pics/"+filename)

    return HttpResponse("上传成功!图片:"+filename)

(2) 使用模型处理上传文件:

将属性定义成models.ImageField类型

pic=models.ImageField(upload_to='cars/')
  • 注意:如果属性类型为ImageField获使用图片处理,那么就需要安装包Pillow
pip install Pillow
  • 图片存储路径
    • 在项目根目录下创建media文件夹
    • 图片上传后,会被保存到“/static/media/cars/图片文件”
    • 打开settings.py文件,增加media_root项
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
  • 使用django后台管理,遇到ImageField类型的属性会出现一个file框,完成文件上传

分页操作

  • Django提供了一些类实现管理数据分页,这些类位于django/core/paginator.py中

Paginator对象

  • Paginator(列表,int):返回分页对象,参数为列表数据,每面数据的条数

属性

  • count:对象总数
  • num_pages:页面总数
  • page_range:页码列表,从1开始,例如[1, 2, 3, 4]

方法

  • page(num):下标以1开始,如果提供的页码不存在,抛出InvalidPage异常

异常exception

  • InvalidPage:当向page()传入一个无效的页码时抛出
  • PageNotAnInteger:当向page()传入一个不是整数的值时抛出
  • EmptyPage:当向page()提供一个有效值,但是那个页面上没有任何对象时抛出

Page对象

创建对象

  • Paginator对象的page()方法返回Page对象,不需要手动构造

属性

  • object_list:当前页上所有对象的列表
  • number:当前页的序号,从1开始
  • paginator:当前page对象相关的Paginator对象

方法

  • has_next():如果有下一页返回True
  • has_previous():如果有上一页返回True
  • has_other_pages():如果有上一页或下一页返回True
  • next_page_number():返回下一页的页码,如果下一页不存在,抛出InvalidPage异常
  • previous_page_number():返回上一页的页码,如果上一页不存在,抛出InvalidPage异常
  • len():返回当前页面对象的个数
  • 迭代页面对象:访问当前页面中的每个对象

代码示例

1. 创建项目mydemo

创建视图pagTest

from django.core.paginator import Paginator

def pagTest(request, pIndex):
    list1 = AreaInfo.objects.filter(aParent__isnull=True)
    p = Paginator(list1, 10)
    if pIndex == '':
        pIndex = '1'
    pIndex = int(pIndex)
    list2 = p.page(pIndex)
    plist = p.page_range
    return render(request, 'booktest/pagTest.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})

配置url

url(r'^pag(?P<pIndex>[0-9]*)/$', views.pagTest, name='pagTest'),

定义模板pagTest.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<ul>
{%for area in list%}
<li>{{area.id}}--{{area.atitle}}</li>
{%endfor%}
</ul>

{%for pindex in plist%}
{%if pIndex == pindex%}
{{pindex}}&nbsp;&nbsp;
{%else%}
<a href="/pag{{pindex}}/">{{pindex}}</a>&nbsp;&nbsp;
{%endif%}
{%endfor%}
</body>
</html>

富文本编辑器

Django集成UEditor (封装成应用) 百度富文本编辑器

http://ueditor.baidu.com/website/

使用效果

测试环境

  • ubuntu 16.04
  • python3.5.2
  • django1.11.7

目前测试解决了出现的以下两个问题,都是python版本问题

  • error1
# name 'file' is not defined
 controller.py  68# jsonfile = file(config_path)
 jsonfile = open(config_path)
  • error2
File "/home/yc/py6/myproject-test/ueditor/controller.py", line 45, 
in buildFileName
for key, value in texts.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'

controller.py  45# for key, value in texts.iteritems():
for key, value in texts.items():

配置方法

1,下载解压ueditor文件包,放置在项目中.,作为一个应用目录

myproject:
    manage.py  myproject  static     ueditor
    myadmin    myweb      templates 

uediter文件夹包括以下:
    controller.py   __init__.py   msyhbd.ttf   UE/             urls.py
    controller.pyc  __init__.pyc  __pycache__  ueconfig.json  urls.pyc

2,打开settings.py,给INSTALLED_APPS加入应用ueditor

INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'myadmin',
        'myweb',
        'ueditor',
    ]

3,检查一下settings.py是否设置好static静态目录,可参考如下设置

STATIC_URL = '/static/'
#静态目录
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

4,打开django项目的urls.py文件,添加ueditor的url路由配置

myproject/myproject/urls.py:

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^ueditor/', include('ueditor.urls')),
    url(r'^admin/',include('myadmin.urls')),
    url(r'^',include('myweb.urls')),
]

5,上面步骤配置完成之后,基本可以使用了。

ueditor配置可能需要根据你的项目具体情况修改。 
ueditor前端配置文件,在ueditor/UE/ueditor.config.js 
ueditor后端配置文件,在ueditor/ueconfig.json 具体配置可参考ueditor官网

此时可以在需要使用富文本编辑器的位置设置一下代码:
html:
    <link rel="stylesheet" type="text/css" href="/ueditor/UE/third-party/SyntaxHighlighter/shCoreDefault.css">
    <script type="text/javascript" src="/ueditor/UE/third-party/SyntaxHighlighter/shCore.js"></script>
    <script type="text/javascript" src="/ueditor/UE/ueditor.config.js"></script>
    <script type="text/javascript" src="/ueditor/UE/ueditor.all.min.js"></script>
    <script type="text/javascript" src="/ueditor/UE/lang/zh-cn/zh-cn.js"></script>


    <div class="am-form-group">
        <label for="user-intro" class="am-u-sm-3 am-form-label">商品简介</label>
        <div class="am-u-sm-9">
            <!-- <textarea name="descr" class="" rows="10" id="user-intro" placeholder="请输入商品简介"></textarea> -->
            <!-- <script id="editor" type="text/plain" style="width:100%;height:500px;"></script> -->
            <script id="editor" name="content" type="text/plain" style="height:500px;"></script>
        </div>
    </div>


    <script type="text/javascript">
        var ue = UE.getEditor('editor');
        SyntaxHighlighter.all();
    </script>

6,其它问题

当前使用 妹子UI 模板 css影响了当前的编辑器的样式

修改,/static/myadmin/assets/css/app.css  379行
.tpl-content-wrapper {
  transition: all 0.4s ease-in-out;
  /*position: relative;*/
  margin-left: 240px;
  z-index: 1101;
  min-height: 922px;
  border-bottom-left-radius: 3px;
}

7,水印功能

  • 上传图片自动加水印 该功能默认没开启。
  • 上传图片加水印功能需要安装PIL
    pip3 install pillow
    
  • 水印相关设置在ueconfig.json末尾:
    "openWaterMark": false,  //是否开启
    "waterMarkText": "我的水印\nhttp://xxxxx.com", //水印内容,建议一行文本
    "waterMarkFont": "msyhbd.ttf",  //字体,中文需要字体支持才不会出错
    "waterMarkSize": 15,    //字体大小
    "waterMarkBottom": 45,  //下边距
    "waterMarkRight": 155   //右边距
    

Django部署(Apache)

在前面的章节中我们使用python3 manage.py runserver来运行服务器。这只适用测试环境中使用。

正式发布的服务,我们需要一个可以稳定而持续的服务器,比如Apache, Nginx, IIS等,本文将以 Apache为例。

使用Apachemod_wsgi部署Django 是一种久经考验的将Django投入生产的方法。

mod_wsgi是一个Apache模块,可以托管任何Python WSGI应用程序,包括Django。

Django将使用任何支持mod_wsgi的Apache版本。

测试环境

说明

  • Ubuntu 16.04
  • Python 3.5.2
  • Django 1.11.7
  • Apache 2.4

配置步骤

1,Apache2安装

Apache2安装
sudo apt-get install apache2

查看版本

apachectl -v

Server version: Apache/2.4.18 (Ubuntu)

Server built: 2017-09-18T15:09:02

2,确保有127.0.0.1 localhost,没有就加上。

sudo vim /etc/hosts

127.0.0.1       localhost
127.0.0.1       www.pyweb.cn

3,打开浏览器 输入 127.0.0.1或localhost

出现 Apache2 Ubuntu Default Page

或It works!

则成功

4,安装apache2解析python的包 wsgi程序包

sudo apt-get install libapache2-mod-wsgi-py3

安装完成后 进入 /usr/lib/apache2/modules 目录
cd /usr/lib/apache2/modules
查看是否存在mod_wsgi.so-3.5

5,配置使apache2加载mod-wsgi包

编辑配置文件
sudo vim /etc/apache2/apache2.conf

在文件的最后 添加

LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so-3.5

6,创建网站配置文件

编辑网站配置文件
sudo vim /etc/apache2/sites-available/myproject.conf

配置内容:
<VirtualHost *:80>
   ServerName www.pyweb.cn
   ServerAdmin py@163.cn
   #wsgi文件目录
   WSGIDaemonProcess python-path=/var/www/myproject
   WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py
   <Directory /var/www/myproject/myproject>
       <Files wsgi.py>
           Require all granted
       </Files>
   </Directory>
   #项目文件目录
   DocumentRoot /var/www/myproject
   <Directory /var/www/myproject>
       Require all granted
   </Directory>
   #静态文件目录
   Alias /static/ /var/www/myproject/static/
   <Directory /var/www/myproject/static/>
       Require all granted
   </Directory>
   #错误日志
   ErrorLog ${APACHE_LOG_DIR}/django-myproject-error.log
   CustomLog ${APACHE_LOG_DIR}/myproject-django.log combined
</VirtualHost>

7,将当前的配置文件创建一个软连接到/etc/apache2/sites-enabled

cd /etc/apache2/sites-enabled

sudo ln -s ../sites-available/myproject.conf ./

8,执行命令 生效当前配置

 sudo a2ensite myproject.conf

如果需要让这个配置失效,可以执行 sudo a2dissite myproject.conf

9,配置Django项目目录及修改seeting.py文件,

首先把myproject项目目录拷贝至 /var/www/目录下

在将其ALLOWED_HOSTS=[]改为

ALLOWED_HOSTS=['www.pyweb.cn'],多个域名可以通过逗号隔开。

10,修改Django的wsgi.py文件

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings"
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyjfive.settings")

from os.path import join,dirname,abspath
PROJECT_DIR = dirname(dirname(abspath(__file__)))

import sys # 4
sys.path.insert(0,PROJECT_DIR)


from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

最后:重启apache2

sudo service apache2 restart

浏览器访问

http://www.pyweb.cn/

浏览器错误 500

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at [no address given] to inform them of the time this error occurred,
and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache/2.4.18 (Ubuntu) Server at www.py6web.com Port 80
  • 查看apache2的错误日志
cd /var/log/apache2/

File "/var/www/myproject-test/myproject/wsgi.py", line 17, in <module>, referer: http://www.pyweb.com/
from django.core.wsgi import get_wsgi_application, referer: http://www.pyweb.com/
ImportError: No module named 'django', referer: http://www.pyweb.com/
  • 问题分析
进入项目目录,使用命令 pip3 show Djando 查看当前是否已经安装django
---
Metadata-Version: 1.1
Name: Django
Version: 1.11.8

切换至root用户 sudo su 

进入python3的shell模式
python3
#加载django模块
import django
#错误:No module named 'django'
  • 解决方案
在当前root用户下 安装django
sudo su
pip3 install django==1.11
59
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!