Reputation: 311
I'm trying to display image in template with get_absolute_url model method.
model:
class UserData(models.Model):
......
photo = models.ImageField(upload_to = 'photo/', blank=True)
def __unicode__(self):
return '%s%s' %(self.last_name, self.photo)
def get_absolute_url(self):
return reverse("user_edit", kwargs={"pk": self.id)
urls:
url(r'^entry/(?P<pk>\d+)/edit/$',views.UserUpdateView.as_view(), name='user_edit')
template:
<img src="{{ userdata.get_absolute_url }}"/>
and can successfully get url in template as:
but if I add one more argument in
return reverse("user_edit", kwargs={"pk": self.id, 'photo':self.photo})
I receive error:
NoReverseMatch at /entry/1/edit/
Reverse for 'user_edit' with arguments '()' and keyword arguments '{'pk': 1,'photo': <ImageFieldFile: photo/_IGP7076.jpg>}' not found. 1 pattern(s) tried: ['entry/(?P<pk>\\d+)/edit/$']
What's wrong? Thanks in advance.
Upvotes: 0
Views: 763
Reputation: 3610
If your MEDIA
settings are configured properly, you can retrieve the relative path of the image using the url
property like so:
<img src="{{ userdata.photo.url }}"/>
https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.fields.files.FieldFile.url
Upvotes: 2
Reputation: 37856
your url pattern does not match:
url(r'^entry/(?P<pk>\d+)/edit/$',views.UserUpdateView.as_view(), name='user_edit')
should be:
url(r'^entry/(?P<pk>\d+)/(?P<photo>[^\/]*)/edit/$',views.UserUpdateView.as_view(), name='user_edit')
but I would not pass photo url via urlconf. you should rethink your app design for this.
Since you have user object in your context, then you can retrieve his photo url via user.photo.url
then no need to pass the photo in url.
Upvotes: 1