I have two models with ImageField
. I am using sorl-thumbnail
to generate thumbnail. The first model has a form binded to it while the second gets its ImageField
populated from the first one, when it is saved.
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()
If I pass these to my templates:
image = NewImage.objects.get(id = 1)
and user = Users.objects.get(id = 1)
.
This displays my image:
{% thumbnail image.thumbnail "200x100" crop="center" as im %}
<img src="..{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
But this only display a square box:
{% thumbnail user.thumbnail "200x100" crop="center" as im %}
<img src="..{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
Both images have a link to images sorl-thumbnail
created in cache folder.
Why is this happening and how can I get my user.thumbnail
displayed?
try this:
one more thing:
instead of doing
upload_image.time_created = timezone.now()
you can change your model to includeauto_now_add=True
which will automatically save the time_created to time it was actually created. like this:Hope it helps.