1、创建带图片类型的模型类试图
class AnimalsImg(models.Model):
ani_name = models.CharField(max_length=20,verbose_name="动物名字")
# ImageField图片类型 upload_to 上传位置
ani_imd = models.ImageField(upload_to='imgs',verbose_name="动物照片")
class Meta:
verbose_name = "动物照片"
verbose_name_plural = verbose_name
db_table = "img"
def __str__(self):
return self.ani_name
2、在settings页面进行配置信息
STATIC_URL = '/static/'
# 1.配置存放照片的路径
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
# 2.配置url,用于访问图片资源
MEDIA_URL='/img/'
3、若需要直接访问需要在路由页面进行添加映射
from rest_framework import routers
from myapp import views
# 导入图片所在文件夹
from django.conf.urls.static import static
# 导入配置信息
from day15wzy import settings
router = routers.DefaultRouter()
router.register('kinds',views.KindsView,'kinds')
router.register('animals',views.AnimalsView,'animals')
urlpatterns = [
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += router.urls