settings里的设置
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname('__file__')))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
models里的设置
cateimg = models.ImageField(upload_to='img/%Y/%m/%d')
forms里的设置
cateimg = forms.ImageField(label='图片', help_text='不能超过5M!')
views里
form = TopicNewForm(request.POST, request.FILES)
if form.is_valid():
try:
old_name = request.FILES['cateimg'].name
user_id = 12345678901
topics = pgccategory.objects.all().order_by('-id')
if len(topics) > 0:
topic_id_max = topics[0].id
else:
topic_id_max = 0
request.FILES['cateimg'].name = 'id_'+str(topic_id_max+1)+'_userid_'+str(user_id)+'_'+old_name
new = pgccategory(catename=request.POST['catename'],
cateimg=request.FILES['cateimg'],
cateinfo=request.POST['cateinfo'],
createuser=request.user)
new.save()
或者
model = User
urls里的设置
from django.conf import settings
from django.conf.urls.static import static
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
在html里面的调用
<img src="/media/{{ ret.img }}">