django 实现将本地图片存入数据库,并能显示在web上的示例

yipeiwu_com5年前Python基础

1. 将图片存入数据库

关于数据库基本操作的学习,请参见这一篇文章:/post/167141.htm

这里我默认,您已经会了基本操作,能在数据库中存图片了,然后,也会用图形界面操作数据库中的数据了

2.这里,我先给出我的代码,能少走些弯路就少走些

a) 项目的urls.py

from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
  path('admin/', admin.site.urls),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

+号后面的一定要写,如果想出来结果的话!否则回报一个 404 的错误

- b) 应用里的models.py

from django.db import models

# Create your models here.
class Person(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()

  def __unicode__(self):
  # 在Python3中使用 def __str__(self):
    return self.name

class IMG(models.Model):
  img = models.ImageField(upload_to='img')
  name = models.CharField(max_length=20)
  def __str__(self):
  # 在Python3中使用 def __str__(self):
    return self.name  

之后,你要会把IMG这个模式推送到数据库。

python ./manage.py makemigrations
python ./manage.py migrate  

c) 应用的views.py

# Create your views here.
def hello(request):
  IMG.objects.filter(name='bg')
  img = IMG.objects.all()
  return render(request, 'Welcome.html',{'img':img})

把img这个参数传过去,传到Welcome.html

- d) Welcome.html

<!DOCTYPE HTML>
<html>

<head>
  <title> welcome </title>
</head>
<body >
    {% for i in img %}
    <img src="{{MEDIA_URL}}{{i.img}}">
    {% endfor %}

</body> 
</html>

e) 设置setting.py

TEMPLATES = [
  {
    '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',
        'django.template.context_processors.media',
      ],
    },
  },
]

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

注意,东西都是配套使用的,如果e中的路径要变的话,a总的+号后面的也要跟着变化

3. 在http://127.0.0.1:8000/admin/网址上面,上传你的图片

以上这篇django 实现将本地图片存入数据库,并能显示在web上的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python数据类型之间怎么转换技巧分享

python数据类型之间怎么转换技巧分享

python数据类型之间怎么转换?数据如果类型不对,在运行中有交集的话就会出现错误,那怎么让两个类型的数据变成同一个类型的呢 首先是字符串,在引号里面的内容都是字符串,包括数字...

对python 读取线的shp文件实例详解

如下所示: import shapefile sf = shapefile.Reader("E:\\1.2\\cs\\DX_CSL.shp") shapes = sf.shapes(...

python简易实现任意位数的水仙花实例

如下所示: # -*- coding: utf-8 -*- # 水仙花数是指一个 n 位正整数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 # 要求:打印输出所有...

浅谈Python中的闭包

Python中的闭包的概念, 在我看来, 就相当于在某个函数中又定义了一个或多个函数, 内层函数定义了具体的实现方式, 而外层返回的就是这个实现方式, 但并没有执行, 除非外层函数调用的...

跟老齐学Python之使用Python查询更新数据库

回顾一下已有的战果:(1)连接数据库;(2)建立指针;(3)通过指针插入记录;(4)提交将插入结果保存到数据库。在交互模式中,先温故,再知新。 复制代码 代码如下: >>&g...