I want to make profiles of users using Django. On the profile page, users can see the profile pictures and posts they've made. Although users can see their posts, they can hardly view their profile pictures. Here I am sharing my profile model and other views.py functions related to that model.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
picture = models.ImageField(null=True,blank=True,upload_to="images/")
views.py
def profilepage(request,id):
user = User.objects.get(pk=id)
profile = Profile.objects.filter(user = user)
posts = NewPost.objects.filter(user = user).order_by("-timestamp")
return render(request, "network/profile.html",{
"user" : user,
"profile" : profile,
"media_url" : settings.MEDIA_URL,
"posts" : posts
})
If I use this function in my template, I can't get the profile picture. If I write my views in the following way, I can get the profile picture but that isn't of the corresponding user. That is, a user views other people's profile pictures on their own profile.
def profilepage(request,id):
user = request.user
profile = Profile.objects.get(pk = id)
posts = NewPost.objects.filter(user = user).order_by("-timestamp")
return render(request, "network/profile.html",{
"user" : user,
"profile" : profile,
"media_url" : settings.MEDIA_URL,
"posts" : posts
})
This function causes no matching with user id and profile picture. I have been trying to relate the User model and Profile model for a couple of days but couldn't fix it. Here is my HTML template.
<img src="{{ MEDIA_URL }}{{ profile.picture }}" alt="image not found." style="border-radius: 50%;" height="100px" width="100px">
Sorry for my bad English.
The main problem was with my HTML template. I should write {{ user.profile.picture.url }}
instead of {{ MEDIA_URL }}{{ profile.picture }}
in my src attribute. Then it would work.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments