i want to load the picture from model. but i get "<QuerySet [<Photo: ira>]>" except of photo.
i have tried to use photo.url, photo.image.url, photo.image, photo.image.image but it does not work
my templtate:
<div id="userInfo">
<img src="{{ photo.url }}" alt="{{ username }}">
<div id="statusAndName">
<h1>{{ username }}</h1>
<h3>{{ status }}</h3>
</div>
</div>
my view:
def UserPage(request,user_num):
user = User.objects.get(pk=user_num)
#get user info
username = user.username
posts = Post.objects.filter(user=user.id)
photo = Photo.objects.filter(user=user.id)
status = user.status
return render(
request,
'userpage.html',
context={'username': username, 'posts': posts, 'status': status, 'photo': photo},
)
my models:
class Photo(models.Model):
"""
A typical class defining a model, derived from the Model class.
"""
# Fields
user = models.OneToOneField('User', on_delete=models.SET_NULL, null=True, help_text="user's id")
photo = models.ImageField()
# Metadata
class Meta:
ordering = ["-user"]
def __str__(self):
"""
String for representing the MyModelName object (in Admin site etc.)
"""
return self.user.username
CodePudding user response:
I think that the problem is because the object Photo
has a sub-field "photo".
Try this:
<div id="userInfo">
<img src="{{ photo.photo.url }}" alt="{{ username }}">
<div id="statusAndName">
<h1>{{ username }}</h1>
<h3>{{ status }}</h3>
</div>
</div>
CodePudding user response:
You're using .filter
which returns a queryset. Since you have a one to one relationship between user and photo, there can be only one photo for a user, so simply change to
photo = Photo.objects.get(user=user.id)
which should return the photo
object if it exists. As Pietro mentioned, you'll need to use photo.photo.url
in your template.
Side note, depending on how you want to handle errors when the photo does not exist, you can either handle DoesNotExist
errors or keep using .filter
and get the first item if it exists