I have a social media website that will allow a user to view another users profile page by clicking their username from one of their posts that appears in the feed section of my page. I have view_profile view created but need to pass in the desired users username into the view, to only show posts, activity, etc... made by that specific user. How do i pass the username into my view?
view_profile.html
<section id="main_feed_section" >
{% for post in posts %}
<div >
<section >
<h1> <a href="{% url 'view_profile' %}">{{ post.user_id.username }}</a>{{ post.title }}</h1>
</section>
<section >
<p>{{ post.caption }}</p>
</section>
<section >
<p>{{ post.date_posted }}</p>
</section>
</div>
{% endfor %}
</section>
views.py
def view_profile(request):
account = "logan9997" #if a post made by logan9997 was clicked
posts = [post for post in Posts.objects.all()
if post.user_id.username == account]
followers = [follower for follower in Relationships.objects.all()
if follower.acc_followed_id.username == account]
context = {
"title":account,
"posts":posts,
"followers":followers
}
return render(request, "myApp/view_profile.html", context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("home/", views.home, name="home"),
path("create_post/", views.create_post, name="create_post"),
path('view_profile/<str:username>', views.view_profile, name="view_profile"),
]
CodePudding user response:
Add a variable to your view:
def view_profile(request, account):
...
And urls:
path('view_profile/<str:account>', ...)
Then you can go to url: localhost:8000/view_profile/logan9997
.
You can do it better with User
id:
path('view_profile/<int:pk>', ...)
def view_profile(request, pk):
account = User.objects.get(id=pk).username
...
And go for: localhost:8000/view_profile/1
This is very not Django-style:
posts = [post for post in Posts.objects.all()
if post.user_id.username == account]
Use filter()
method instead:
posts = Posts.objects.filter(user_id__username=account)
# and
followers = Relationships.objects.filter(acc_followed_id__username=account)