我已经定义了一个带有'pic'图像字段的模型:
class Photo(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
teaser = models.TextField('teaser', blank=True)
pic = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/default.jpg')
created=models.DateTimeField(default=datetime.datetime.now)
pub_date=models.DateTimeField(default=datetime.datetime.now)
categories = models.ManyToManyField(Category, blank=True)
likes = models.IntegerField(default=0)
dislikes = models.IntegerField(default=0)
visits = models.IntegerField(default=0)
slug = models.CharField(max_length=100, unique=True, blank=True)
以下是上传表格:
class PhotoForm(forms.ModelForm):
class Meta:
model= Photo
fields = ( 'title', 'pic','body', 'categories')
发表这个观点:
@staff_member_required
def add_photo(request):
if request.method == 'POST':
form = PhotoForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.info(request, "photo was added")
return render(request, 'home.html')
else:
messages.info(request, 'form not valid')
return render(request, 'home.html')
if request.method == 'GET':
form = PhotoForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'photo/add_photo.html', args)
问题在于正在保存照片对象并上传文件但未显示图像。
<div class="photo_body"><img src="pic_folder/someimage.jpg" ></div>
我也设置了
MEDIA_ROOT = '/path/to/my_project/pic_folder'
并运行manage.py collectstatic,但他们没有解决问题。
我真的对此感到困惑。非常感谢您的提示。
答案 0 :(得分:2)
首先在项目目录中创建一个名为media
的文件夹。
Django会自动将您上传的所有图片存储在media/pic_folder/
内。
在settings.py
文件中,添加以下内容:
MEDIA_URL = '/media/'
MEDIA_ROOT = '/path_to/media/' # write the path to the media folder you just created.
在urls.py
文件中,在顶部添加以下行:
from django.conf import settings
from django.conf.urls.static import static
并在最后添加以下行:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
如下所示:
urlpatterns = patterns('',
# Your urls here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
最后,在你的templates
:
<img src="{{MEDIA_URL}}pic_folder/someimage.jpg" />