「Python-Django」django 实现将本地图片存入数据库,并能显示在web上

本文详细介绍如何在Django项目中实现图片上传至数据库及在网页上展示的全过程,包括urls配置、models定义、views处理及HTML模板显示。

1. 将图片存入数据库

关于数据库基本操作的学习,请参见这一篇博客:https://www.cnblogs.com/leejy/p/6745186.html

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

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/网址上面,上传你的图片

土拍你

--------------------- 本文来自 竦貊 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/Inuyasha_1314/article/details/80531900?utm_source=copy 

转载于:https://www.cnblogs.com/wrxblog/p/9727886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值