使用媒体文件

一、在一般的后台管理系统中都会增加图片获取视频,需要展现在前端

  • 1、在models.py中定义上传图片的数据模型

    class CourseOrgModel(models.Model):
        """
        创建一个课程机构的模型
        """
        name = models.CharField(max_length=50, verbose_name='机构名称')
        desc = models.TextField(verbose_name='机构描素')
        catgory = models.CharField(max_length=20, choices=(('pxjg', '培训机构'), ('gx', '高校'), ('gr', '个人')), default='pxjg',
                                  verbose_name='机构类别')
        click_nums = models.IntegerField(default=0, verbose_name='点击数')
        fav_nums = models.IntegerField(default=0, verbose_name='收藏数')
        image = models.ImageField(upload_to='images/org/%Y/%m', verbose_name='机构图片')
        address = models.CharField(max_length=100, verbose_name='机构地址')
        city = models.ForeignKey('CityModel', on_delete=models.CASCADE, verbose_name='机构所在城市')
        create_at = models.DateTimeField(auto_now_add=True, null=False, verbose_name='添加时间')
        update_at = models.DateTimeField(auto_now=True, null=False, verbose_name='修改时间')
    
        class Meta(object):
            verbose_name = '课程机构'
            verbose_name_plural = verbose_name
    
  • 2、在settings.py中配置上传图片的文件夹

    # 配置上传图片的地址
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    
  • 3、在xadmin的后台管理系统中上传图片

  • 4、查看数据库中image字段保存的

    mysql> select * from organization_courseorgmodel\G;
    *************************** 1. row ***************************
            id: 1
          name: 深圳大学
          desc: In my dual profession as an educator and health care provider, I have worked with numerous children infected with the virus that causes AIDS. The relationships that I have had with these special kids have been gifts in my life. They have taught me so many things, but I have especially learned that great courage can be found in the smallest of packages. Let me tell you about Tyler.
    click_nums: 10
      fav_nums: 0
        image: images/org/2018/08/imooc.png
      address: 深圳市
    create_at: 2018-08-04 13:34:19.332699
    update_at: 2018-08-04 13:35:14.672164
      city_id: 3
      catgory: pxjg
    *************************** 2. row ***************************
    
  • 5、视图类中返回数据

    from django.shortcuts import render
    from django.views.generic import View
    
    from organization import models
    
    class OrganizationView(View):
        def get(self, request, *args, **kwargs):
            # 所有的城市
            all_city = models.CityModel.objects.all()
            # 所有的课程
            all_course = models.CourseOrgModel.objects.all()
            return render(request, 'org-list.html', locals())
    
        def post(self, request, *args, **kwargs):
            pass
    
  • 6、前端html页面中直接取数据库返回的image的地址(查看数据库的时候只有从images/...,我们需要在前端中配置media/images...)

    <img width="200" height="120" class="scrollLoading" data-url="' MEDIA_URL  course_org.image '"/>
    
  • 7、在settings.py中配置media的中间件

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': ['templates'],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    ...
                    'django.template.context_processors.media'
                ],
            },
        },
    ]
    
  • 8、配置url读取本地文件

    from django.urls import path, include, re_path
    import xadmin
    from users.views import index
    from django.views.static import serve
    from django.conf import settings
    
    urlpatterns = [
        path('xadmin/', xadmin.site.urls),
        path('', index.IndexView.as_view(), name='home'),
        ...
        # 配置访问本地的资源地址
        re_path(r'^media/(?P<path>.*)', serve, {"document_root": settings.MEDIA_ROOT}),
    ]
    

results matching ""

    No results matching ""