使用django框架上传图片并显示出来(Form模块和ModelForm模块)

本文详细介绍了如何在Django项目中使用Form和ModelForm模块创建表单、处理POST请求以及上传图片。包括URL配置、模型定义、HTML模板和视图函数的编写。
摘要由CSDN通过智能技术生成

一、Form模块

1、创建url路径

 path('upload/form/', upload.upload_form),

2、 创建表

class Boss(models.Model):
    name = models.CharField(verbose_name="姓名", max_length=32)
    age = models.IntegerField(verbose_name="年龄")
    img = models.CharField(verbose_name="头像", max_length=128)

3、html

{% extends 'header.html' %}

{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">{{ title }}</h3>
            </div>
            <div class="panel-body">
                <form method="post" enctype="multipart/form-data" novalidate>
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label>{{ field.label }}</label>
                            {{ field }}
                            <span class="error-msg" style="color: red">{{ field.errors.0 }}</span>
                        </div>
                    {% endfor %}
                    <button type="submit" class="btn btn-primary">提交</button>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

4、视图函数

from django.shortcuts import render, HttpResponse
from app01.utils.bootstrap import BootStrapForm, BootStrapModelForm
from django import forms
import os
from app01 import models

from django.conf import settings
class UpForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']
    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")


def upload_form(request):
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request, "upload_form.html", {"form": form, "title": title})

    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 1、读取图片的内容,写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get("img")
        db_file_path = os.path.join("static", "img", image_object.name)
        # file_path = os.path.join("app01", "static", "img", image_object.name)
        # 保存下来是决对路径
        # file_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        file_path = os.path.join("media", image_object.name)
        f = open(file_path, mode="wb")
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        # 2、将图片路径写入到数据库中
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=file_path,
        )
        return HttpResponse("...")
    return render(request, "upload_form.html", {"form": form, "title": title})

二、ModelForm模块(显现出上传图片)

1、url

   path('upload/modelform/', upload.upload_modelform),

    # 城市
    path('city/list/', city.city_list),
    path('city/add/', city.city_add),

 2、设置图片的存放路径(防止出现图片混乱)

(1)创建media目录

(2)在setting.py中配置

import os

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

(3)在url.py中配置

from django.urls import path, re_path
from django.views.static import serve
from django.conf import settings

urlpatterns = [

    re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}, name='media'),
]

3、创建表

class City(models.Model):
    "城市"
    name = models.CharField(verbose_name="名称", max_length=32)
    count = models.IntegerField(verbose_name="人口")

    # 本质上数据库也是CharField,自动保存数据
    img = models.FileField(verbose_name="Logo", max_length=128, upload_to='city/')

4、url

 # 城市
    path('city/list/', city.city_list),
    path('city/add/', city.city_add),

5、html

{% extends 'header.html' %}
{% block css %}

{% endblock %}
{% block content %}
    <div>
        <div class="container">
            <div style="margin-bottom: 10px">
                <a class="btn btn-success" href="/city/add/" target="_blank">
                    <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                    新建城市
                </a>
            </div>
            <div class="panel panel-default">
                <div class="panel-body">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    城市列表
                </div>
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>名称</th>
                        <th>人口</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in queryset %}
                        <tr>
                            <td>{{ obj.id }}</td>
                            <td>
                                <img src="/media/{{ obj.img }}" style="height: 80px;">
                            </td>
                            <td>{{ obj.name }}</td>
                            <td>{{ obj.count }}</td>

                        </tr>
                    {% endfor %}

                    </tbody>
                </table>
            </div>
            <ul class="pagination">
                {{ page_string }}
            </ul>
        </div>

    </div>
{% endblock %}
{% block js %}
{% endblock %}
</body>
</html>

6、视图函数

from django.shortcuts import render,redirect
from app01 import models
from app01.utils.bootstrap import BootStrapForm, BootStrapModelForm

def city_list(request):
    queryset = models.City.objects.all()
    return render(request, 'city_list.html', {'queryset': queryset})

def city_add(request):
    return redirect("/upload/modelform/")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值