温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-05-06 09:54:28 来源:亿速云 阅读:375 作者:小新 栏目:开发技术

这篇文章主要介绍django怎么实现将本地图片存入数据库并能显示在web上,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1. 将图片存入数据库

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

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上

以上是“django怎么实现将本地图片存入数据库并能显示在web上”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI