Django上传的图片未在开发中显示

Django上传的图片未在开发中显示

本文介绍了Django上传的图片未在开发中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 pic图像字段定义了一个模型:

I have defined a model with a 'pic' image field:

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)

问题在于,当保存照片对象并上传文件时,却不显示图像。

The problem is that while photo objects are being saved and the file uploaded but the images are not displayed.

  <div class="photo_body"><img src="pic_folder/someimage.jpg" ></div>

我还设置了

MEDIA_ROOT = '/path/to/my_project/pic_folder'

并运行管理.py collectstatic,但他们没有解决问题。

and run manage.py collectstatic, but they did not solve the problem.

我对此感到非常困惑。因此,感谢您的提示。

I really got confused about this. So appreciate your hints.

推荐答案

首先在项目目录中创建一个名为 media 的文件夹。

First of all make a folder called media in your project's directory.

Django将自动将所有上传的图像存储在 media / pic_folder / 中。

Django will store all your uploaded images inside media/pic_folder/ automatically.

在您的 settings.py 文件中,添加以下内容:

In your settings.py file, add this:

MEDIA_URL = '/media/'

MEDIA_ROOT = '/path_to/media/' # write the path to the media folder you just created.

在您的 urls.py 文件中,添加顶部的以下几行:

In your urls.py file, add the following lines at the top:

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)

最后,在您的模板中:

<img src="{{MEDIA_URL}}pic_folder/someimage.jpg" />

这篇关于Django上传的图片未在开发中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 05:35