使用django模板显示存储在ImageField中的图像

时间:2017-07-29 00:55:47

标签: python django nginx django-templates digital-ocean

我在生产环境中即将使用digitalocean完全部署我的应用程序,但我遇到了这个小问题。我一直试图显示用户上传的图像,但它们似乎没有显示,即使它们上传并保存在'/ home / kingiyk / stylplus / static /'

这是我的代码

 settings.py

 STATIC_ROOT = '/home/kingiyk/stylplus/static/'
 STATIC_URL = '/static/'


MEDIA_ROOT = '/home/kingiyk/stylplus/static/'
MEDIA_URL = '/media/'


 Image model (models.py)
    class Image(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                         related_name='images_created')
    title = models.CharField(max_length=2000)
    slug = models.SlugField(max_length=200,
                        blank=True)
    url = models.URLField()
    image = models.ImageField(upload_to='/home/kingiyk/stylplus/static/')
    description = models.TextField(blank=True, null=True)
    created = models.DateField(auto_now_add=True,
                                            db_index=True)
    users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                                related_name='images_liked', blank=True)



class Meta:
    ordering = ('-created',)




def __str__(self):
    return self.title


def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.title)
        super(Image, self).save(*args, **kwargs)

def get_absolute_url(self):
    return reverse('images:detail', args=[self.id, self.slug])

请更加重视imagefield(upload_to)

nginx conf

server {
listen 80;
server_name 67.207.87.22;

location = /favicon.ico { access_log off; log_not_found off;

}

location /static/ {
    alias /home/kingiyk/stylplus/static/;
}

location /media/ {

    alias /home/kingiyk/stylplus/media/;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/kingiyk/stylplus/stylplus.sock;
   }
}

views.py

def image_detail(request, id, slug):
    image = get_object_or_404(Image, id=id, slug=slug)



    comments = image.comments.all()




   if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)
    #if comment_form.is_valid():
    new_comment = comment_form.save(commit=False)
    new_comment.image = image
    new_comment.user = request.user
    new_comment.save()
  else:
    comment_form = CommentForm()      

return render(request, 'images/image/detail.html', {'section': 'images', 'image': image, 'comments': comments,'comment_form': comment_form})

HTML

    <a href="{{ image.image.url }}">
        <img src="{{ image.image.url }}" alt="{{ image.title }}" class="image-detail"/>
    </a>

预计html会显示图像,但不会。尽管{{image.title}}和{{image.description}}分别显示标题和说明。

应该注意到

但是,{{image.image.url}}没有。所以我认为它可能不是来自nginx conf。

我正在使用django 1.8.6

其他所有事情都很好,只是上传的图片不显示。 谢谢你的时间

0 个答案:

没有答案