Django教程(五) 上传及显示

目录:

上传及显示

model.py
from django.db import models

# Create your models here.

class Profile(models.Model):
   name = models.CharField(max_length = 50)
   picture = models.ImageField(upload_to = 'pictures/')
复制代码
views.py
from django.shortcuts import render
from django import forms
from .models import Profile
# Create your views here.

class ProfileForm(forms.Form):
   name = forms.CharField(max_length = 100)
   picture = forms.ImageField()


def saveProfile(request):


    if request.method == "POST":
        # Get the posted form
        MyProfileForm = ProfileForm(request.POST, request.FILES)

        if MyProfileForm.is_valid():
            profile = Profile()
            profile.name = MyProfileForm.cleaned_data["name"]
            profile.picture = MyProfileForm.cleaned_data["picture"]
            profile.save()

    else:
        MyProfileForm = ProfileForm()

    return render(request, 'saved.html', {"form":MyProfileForm})

def showImages(request):
    objs = Profile.objects.all()
    print objs
    return  render(request,"list.html",{"pics":objs})

复制代码
工程目录的urls
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings


urlpatterns = [
    url(r'imgapp/',include("imgapp.urls")),
    url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

复制代码
工程目录settings增加下列代码

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'imgapp'
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')



复制代码
App目录下的urls
from django.conf.urls import url

from . import views
urlpatterns = [


    url(r'^upload/$',views.saveProfile,name="upload"),
    url(r'^showlist/$',views.showImages,name="showlist"),

]
复制代码
创建templates文件夹,分别创建saved.html,list.html

saved.html上传图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="{{ request.path }}"  method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.name}}<br/>
        {{form.picture}}

        <input type="submit" value="upload">
    </form>

</body>
</html>
复制代码
list.html显示上传的图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% for pic in pics %}

    ![]({{ pic.picture.url }})
    <br/>

    {%endfor%}

</body>
</html>
复制代码

实例代码操作: 显示之前先安装pip install pillow

  • views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from . import models
from django.forms import fields,Form,widgets
from django.http import HttpResponse
# Create your views here.



class uploadForm(Form):
    introduce = fields.CharField(max_length=50)
    picPath = fields.ImageField()



def load(request):
    if request.method == 'GET':
        uploadform = uploadForm()
        return render(request,'upload.html',{'form':uploadform})
    elif request.method == 'POST':
        uploadform = uploadForm(request.POST,request.FILES)
        if uploadform.is_valid():
            Load = models.loadmodel()
            Load.introduce = uploadform.cleaned_data['introduce']
            Load.picPath = uploadform.cleaned_data['picPath']
            Load.save()
            pics = models.loadmodel.objects.all()
            return render(request,'pics.html',{'pics':pics})

    else:
        return render(request,'upload.html')


def showAll(request):
    pics = models.loadmodel.objects.all()
    return render(request,'pics.html',{'pics':pics})



复制代码
  • urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'upload/$',views.load,name='upload'),
    url(r'showAll/$',views.showAll,name='showAll'),
]
复制代码
  • models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models


    # Create your models here.
class loadmodel(models.Model):
    introduce = models.CharField(max_length=50)
    picPath = models.ImageField(upload_to='pictures/',)
复制代码
  • pics.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片显示</title>
</head>
<body>

        <h1>图片显示</h1>
        {% for pic in pics %}
        ![]({{ pic.picPath.url }})
        <br>

        {% endfor %}


</body>
</html>
复制代码
  • upload.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
</head>
<body>
    <form action="" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        描述:{{form.introduce}}<br>
        {{form.picPath}}<br>

        <input type="submit" value="确定上传">

    </form>

</body>
</html>
复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值