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设计】。

相关文章

Django3.0 异步通信初体验(小结)

Django3.0 异步通信初体验(小结)

此前博主曾经写过一篇博文,介绍了Django3.0的新特性,其中最主要的就是加入对ASGI的支持,实现全双工的异步通信。 2019年12月2日,Django终于正式发布了3.0版本。怀着...

Python输出汉字字库及将文字转换为图片的方法

Python输出汉字字库及将文字转换为图片的方法

用python输出汉字字库 问题1:假设我们知道汉字编码范围是0x4E00到0x9FA5,怎么从十六进制的编码转成人类可读的字呢? 问题2:怎么把unicode编码的字写入文件呢,如果直...

详谈python3 numpy-loadtxt的编码问题

如下所示: data_array = np.loadtxt(filename, #文件名 delimiter=',', #分隔符...

Python3 单行多行万能正则匹配方法

可匹配单行,也支持换行匹配 [\s\S]*? 加上括号,效果更好 ([\s\S]*?) 以上这篇Python3 单行多行万能正则匹配方法就是小编分享给大家的全部内容了,希...

详解Python的Django框架中的模版继承

在实际应用中,你将用 Django 模板系统来创建整个 HTML 页面。 这就带来一个常见的 Web 开发问题: 在整个网站中,如何减少共用页面区域(比如站点导航)所引起的重复和冗余代码...