1

I am working on a Django project. I have to display database data in the Django template but I can't find out my mistake in my code that is not allowing me to display data on the HTML page.

views.py

def viewposts(request):
     posts = NewPost.objects.all()

     return render(request,"network/index.html",{
         "posts" : posts,
     })

Here is my model:

models.py

class NewPost(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    post = models.TextField()
    timestamp = models.DateTimeField(auto_now_add = True)

    def __str__(self):
         return f"post : {post} || user: {user} || timestamp: {timestamp} "

HTML template

<div id="posts">
        {% for posts in posts %}
            <ul>
                <li>
                    <h4>{{ posts.user }} || {{ posts.timestamp }}</h4>
                    <h3>{{ posts.post }}</h3>
                </li>
            </ul>   
        {% empty %}
            <h6>No post availabel 😔</h6>
        {% endfor %}
    </div>

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"),
   path("index/",views.NewPostMaker,name="post"),
   path("index/",views.viewposts,name="posts")
]

I know I have done a silly mistake on any part of my code but I can hardly find it out. When I fill-up the form, data is stored in the database but I can't display them on the HTML page.

1
  • You have two index/ patterns, hence it will fire the NewPostMaker, not the viewposts. Commented Nov 3, 2021 at 11:26

1 Answer 1

1

You defined two paths for index/. This means that if the user visits the index/ URL, the first view will "fire" and render the template. As a result it will fire NewPostMaker, not viewposts.

You thus should define one view, where you probably will have to merge the logic of the two views into one, and thus implement this as:

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'),
   path('index/', views.viewposts, name='posts')
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.