Django meida(admin后台上传图片并可访问)

1、models

class MediaTest(models.Model):
    picture_url = models.ImageField(
        null=True,
        blank=True,
        upload_to='image',
        max_length=200)

    class Meta:
        db_table = 'media_test'

2、admin 

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from models import MediaTest

# Register your models here.


class MangeMedia(admin.ModelAdmin):
    fields = ('picture_url',)


admin.site.register(MediaTest, MangeMedia)

 

 

3、在settings.py中设置:

MEDIA_ROOT =BASE_DIR#os.path.join(BASE_DIR, 'media') 
MEDIA_URL
= '/media/'

4、配置url:

from django.conf.urls import url
from django.contrib import admin
from settings import MEDIA_ROOT
from django.views.static import serve

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}),
]

5、上传文件

 

 

6、访问图片

 

 

posted @ 2017-12-18 23:22  lplucky  阅读(3574)  评论(0编辑  收藏  举报