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、訪問圖片

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM