Django第10天

图片上传及分页

上传图片

在python中进行图片操作,需要安装包PIL。

pip install Pillow

在Django中上传图片包括两种方式:

  • 在管理页面admin中上传图片
  • 自定义form表单中上传图片

上传图片后,将图片存储在服务器上,然后将图片的路径存储在表中。

创建包含图片的模型类

将模型类的属性定义成models.ImageField类型。

1)打开booktest/models.py文件,定义模型类PicTest。

class PicTest(models.Model):
    pic = models.ImageField(upload_to='booktest/')

2)回到命令行中,生成迁移。

python manage.py makemigrations
python manage.py migrate

3)打开booktest/migrations/0001_initial.py文件,删除AreaInfo部分,因为这个表已经存在。
4)因为当前没有定义图书、英雄模型类,会提示“是否删除”,输入“no”后回车,表示不删除。
5)打开test5/settings.py文件,设置图片保存路径。
因为图片也属于静态文件,所以保存到static目录下。

MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")

6)在static目录下创建media目录,再创建应用名称的目录,此例为booktest。


自定义form表单中上传图片

1)打开booktest/views.py文件,创建视图pic_upload。

def pic_upload(request):
    return render(request,'booktest/pic_upload.html')

2)打开booktest/urls.py文件,配置url。

url(r'^pic_upload/$', views.pic_upload),

3)在templates/booktest/目录下创建模板pic_upload.html。
在模板中定义上传表单,要求如下:

  • form的属性enctype="multipart/form-data"
  • form的method为post
  • input的类型为file
<html>
<head>
    <title>自定义上传图片</title>
</head>
<body>
    <form method="post" action="/pic_handle/" enctype="multipart/form-data">
        {%csrf_token%}
        <input type="file" name="pic"/><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

4)打开booktest/views.py文件,创建视图pic_handle,用于接收表单保存图片。
request对象的FILES属性用于接收请求的文件,包括图片。

from django.conf import settings
from django.http import HttpResponse
...
def pic_handle(request):
    """
    上传图片处理
    :param request:
    :return:
    """
    pic = request.FILES.get('pic')
    print(pic.name)
    save_path = '{}/booktest/{}'.format(settings.MEDIA_ROOT,pic.name)
    with open(save_path,'wb') as f:
        for content in pic.chunks():
            f.write(content)
    # 在数据库中保存上传记录
    PicTest.objects.create(goods_pic='booktest/{}'.format(pic.name))
    return HttpResponse('OK')

5)打开booktest/urls.py文件,配置url。

url(r'^pic_handle/$', views.pic_handle),

6)运行服务器,在浏览器中输入如下网址:

http://127.0.0.1:8000/pic_upload/

显示图片

1)打开booktest/views.py文件,创建视图pic_show。

from booktest.models import PicTest
def pic_show(request):
    pic=PicTest.objects.get(pk=1)
    print(pic.goods_pic)
    context={'pic':pic}
    return render(request,'booktest/pic_show.html',context)

2)打开booktest/urls.py文件,配置url。

url(r'^pic_show/$', views.pic_show),

3)在templates/booktest/目录下创建模板pic_show.html。

<html>
<head>
    <title>显示上传的图片</title>
</head>
<body>
<img style="width: 380px ; height: 240px" src="/static/media/{{pic.goods_pic}}"/>
</body>
</html>

4)运行服务器,在浏览器中输入如下网址:

http://127.0.0.1:8000/pic_show/

改为回显

修改视图函数

from django.conf import settings
def pic_handle(request):
    """
    上传图片处理
    :param request:
    :return:
    """
    pic = request.FILES.get('pic')
    print(pic.name)
    save_path = '{}/booktest/{}'.format(settings.MEDIA_ROOT,pic.name)
    with open(save_path,'wb') as f:
        for content in pic.chunks():
            f.write(content)
    # 在数据库中保存上传记录
    # PicTest.objects.create(goods_pic='booktest/{}'.format(pic.name))
    # return HttpResponse('OK')

    pic_file = PicTest.objects.create(goods_pic='booktest/{}'.format(pic.name))
    # 获取路径
    print(pic_file.goods_pic)
    context = {'pic': pic_file}
    print(context.get('pic'))
    return render(request,'booktest/pic_show.html',context)

分页

Django提供了数据分页的类,这些类被定义在django/core/paginator.py中。 类Paginator用于对列进行一页n条数据的分页运算。类Page用于表示第m页的数据。

Paginator类实例对象
  • 方法init(列表,int):返回分页对象,第一个参数为列表数据,第二个参数为每页数据的条数。
  • 属性count:返回对象总数。
  • 属性num_pages:返回页面总数。
  • 属性page_range:返回页码列表,从1开始,例如[1, 2, 3, 4]。
  • 方法page(m):返回Page类实例对象,表示第m页的数据,下标以1开始。
Page类实例对象
  • 调用Paginator对象的page()方法返回Page对象,不需要手动构造。
  • 属性object_list:返回当前页对象的列表。
  • 属性number:返回当前是第几页,从1开始。
  • 属性paginator:当前页对应的Paginator对象。
  • 方法has_next():如果有下一页返回True。
  • 方法has_previous():如果有上一页返回True。
  • 方法len():返回当前页面对象的个数。
示例

1)在areatest/views.py文件中创建视图page_test。

from django.shortcuts import render

# Create your views here.
from django.core.paginator import Paginator
from areatest.models import AreaInfo
...
#参数pIndex表示:当前要显示的页码
def page_test(request,pIndex):
    #查询所有的地区信息
    list1 = AreaInfo.objects.filter(aParent__isnull=True)
    #将地区信息按一页10条进行分页
    p = Paginator(list1, 10)
    #如果当前没有传递页码信息,则认为是第一页,这样写是为了请求第一页时可以不写页码
    if pIndex == '':
        pIndex = '1'
    #通过url匹配的参数都是字符串类型,转换成int类型
    pIndex = int(pIndex)
    #获取第pIndex页的数据
    list2 = p.page(pIndex)
    #获取所有的页码信息
    plist = p.page_range
    #将当前页码、当前页的数据、页码信息传递到模板中
    return render(request, 'areatest/page_test.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})

2)在areatest/urls.py文件中配置url。

url(r'^page(?P<pIndex>[0-9]*)/$', views.page_test),

3)在templates/areatest/目录下创建page_test.html模板文件。

<html>
<head>
    <title>分页</title>
</head>
<body>
显示当前页的地区信息:<br>
<ul>
{%for area in list%}
<li>{{area.id}}--{{area.atitle}}</li>
{%endfor%}
</ul>
<hr>
显示页码信息:当前页码没有链接,其它页码有链接<br>
{%for pindex in plist%}
    {%if pIndex == pindex%}
        {{pindex}}&nbsp;&nbsp;
    {%else%}
        <a href="/page{{pindex}}/">{{pindex}}</a>&nbsp;&nbsp;
    {%endif%}
{%endfor%}
</body>
</html>

4)运行服务器,在浏览器中输入如下网址:

http://127.0.0.1:8000/page/
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容