I am currently exploring the Django web framework and aim to create a homepage similar to Twitter or Facebook. Users should be able to post updates and view others' posts, but I am encountering an issue where logged-in users cannot see their own posts on the homepage. Below is the views function I have implemented for this scenario.
views.py
def index(request):
posts = NewPost.objects.all().order_by("-timestamp")
if request.user.is_authenticated:
if request.method == "POST":
post = NewPostForm(request.POST)
user = request.user
timestamp = datetime.now()
if post.is_valid:
post = post.save(commit=False)
postdata = NewPost(post=post,user=user,timestamp=timestamp)
postdata.save()
return render(request,"network/index.html",{
"post" : post,
"user" : user,
"timestamp" : timestamp
})
else:
post = NewPostForm()
return render(request,"network/index.html",{
"post" : post
})
return render(request,"network/index.html",{
"posts" : posts
})
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
]
templates
{% extends "network/layout.html" %}
{% block body %}
<div style="margin: 10px 10px 10px 10px;">
<h1>All Posts</h1>
{% if user.is_authenticated %}
<div class="border border-success" style="margin: 10px 10px 10px 10px;">
<div style="margin: 10px 10px 10px 10px;">
<h3>New Post</h3>
<form action="{% url 'index' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<!-- <textarea name="post" class="form-control" cols="30" rows="5" placeholder="What is in your mind? "></textarea> -->
{{ post.as_table }}
</div>
<input class="btn btn-success" type="Submit" value="Post">
</form>
</div>
</div>
{% endif %}
<div id="posts" class="card">
<div class="card-body">
{% for posts in posts %}
<ul>
<li class="card">
<div class="card-body">
<h5 class="card-title">{{ posts.user }}</h5>
<h6 class="card-subtitle text-muted">{{ posts.timestamp }}</h6>
<h3 class="card-text">{{ posts.post }}</h3>
</div>
</li>
</ul>
{% empty %}
<h6>No post availabel 😔</h6>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
If you encounter issues with disappearing form after clicking the post button, you can check out my video tutorial here