• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 25次浏览 已收录 0个评论

1. 将图片存入数据库

关于数据库基本操作的学习,请参见这一篇文章:https://www.gaodaima.com/article/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<a style="color:transparent">来@源gao*daima.com搞@代#码网</a>):
    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上的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:django 实现将本地图片存入数据库,并能显示在web上的示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址