图像不显示从Django中手动保存到另一个模型的路径

时间:2014-11-27 05:15:53

标签: python django image sorl-thumbnail

我有两个模型ImageField我正在使用sorl-thumbnail生成缩略图。第一个模型有一个绑定到它的表单,而第二个模型在保存时从第一个模型填充ImageField

models.py

#the first model
class NewImage(models.Model):
    thumbnail = models.ImageField(upload_to='photos')
    time_created = models.DateTimeField()
#second
class Users(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=200)
    thumbnail = models.ImageField(upload_to='photos')
    time_created = models.DateTimeField()

forms.py

class ImageForm(forms.ModelForm):
  class Meta:
    model = NewImage
    fields = {'thumbnail'}

views.py

def saveImage(request):
    if request.method == 'POST':
      user = Users.objects.get(id = 1)
      imageForm = ImageForm(request.POST, request.FILES or None)
        if imageForm.is_valid():
            upload_image = imageForm.save(commit=False)
            upload_image.time_created = timezone.now()
            upload_image.save()
            #save image path to user who uploaded it.
            user.thumbnail = upload_image.thumbnail
            user.save()

如果我将这些传递给我的模板: image = NewImage.objects.get(id = 1)user = Users.objects.get(id = 1)

这会显示我的图片:

{% thumbnail image.thumbnail "200x100" crop="center" as im %}
    <img src="..{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}

但这只显示一个方框:

{% thumbnail user.thumbnail "200x100" crop="center" as im %}
    <img src="..{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}

这两个图片都有指向缓存文件夹中创建的图片sorl-thumbnail的链接。

为什么会发生这种情况?如何显示我的user.thumbnail

1 个答案:

答案 0 :(得分:0)

试试这个:

user.thumbnail = upload_image.thumbnail.name
user.save()

还有一件事:

而不是upload_image.time_created = timezone.now() 您可以更改模型以包含auto_now_add=True,这将自动将time_created保存到实际创建的时间。 像这样:

class NewImage(models.Model):
    thumbnail = models.ImageField(upload_to='photos')
    time_created = models.DateTimeField(auto_now_add=True)

希望它有所帮助。