8

[求助] Django 图片路径的问题

 2 years ago
source link: https://www.v2ex.com/t/845045
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Python

[求助] Django 图片路径的问题

  maloneleo88 · 8 小时 21 分钟前 · 300 次点击

用 Django 自带后台,做上传图片功能。预览的时候打不开。

图片正确的路径是:

http://127.0.0.1:8000/media/img/2022/02/13/%E6%9C%AA%E6%A0%87%E9%A2%98-1_z6YBLvG.jpg

后台超级链接的路径是:

http://127.0.0.1:8000/admin/web/detectioninfo/4/change/media/img/2022/02/13/%E6%9C%AA%E6%A0%87%E9%A2%98-1_z6YBLvG.jpg

还没学明白,不知道哪里的问题,求指点

url.py 的 urlpatterns


    re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}, name='media'),

models.py

class DetectionInfo(models.Model):

    img_1 = models.ImageField(verbose_name="现场图", upload_to='img/%Y/%m/%d',blank=True,null=True)

第 1 条附言  ·  6 小时 52 分钟前

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = 'media/'
3 条回复    2022-04-05 19:10:51 +08:00

uasier

uasier      6 小时 35 分钟前

import time
from django.db import models

# Create your models here.
def image_upload_to(instance, filename):
type = filename.split(".")[-1]
now_time = time.strftime('%Y/%m/%d/%H%M%S', time.localtime())
return 'image/{now_time}.{type}'.format(now_time=now_time, type=type)

class Image(models.Model):
"""
图片文件表
"""
objects = models.Manager()
username = models.CharField(max_length=128, blank=False, default="") # 用户名
user_ip = models.CharField(max_length=16, blank=False, default="") # ip
img_name = models.CharField(max_length=128, blank=False, default="") # 图片文件名
img = models.ImageField(upload_to=image_upload_to) # 图片存储地址
created_time = models.DateTimeField(auto_now_add=True) # 记录创建时间

class Meta:
"""
对当前表进行相关设置:
"""
ordering = ('id',)
db_table = 'image'
verbose_name = '图片表'
verbose_name_plural = verbose_name

grimpil

grimpil      6 小时 4 分钟前

先确认一下 BASE_DIR 是啥吧

veoco

veoco      5 小时 49 分钟前

改成 MEDIA_URL = '/media/'

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK