Is there a way to create a Twitter-inspired homepage using Django?

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

Answer â„–1

  • To display the form, ensure that the user is passed in the context within the condition where the user is authenticated.
  • Add all posts to the context for them to be visible on the page.

Follow these steps:

def index(request):
   posts = NewPost.objects.all().order_by("-timestamp")

   if request.user.is_authenticated:
      user = request.user # Update this line
      if request.method == "POST":
          post = NewPostForm(request.POST)
          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,
              "posts" : posts,
              "user" : user,
              "timestamp" : timestamp
          })

      else:
          post = NewPostForm()
          return render(request,"network/index.html",{
              "post" : post,
              "posts" : posts,
              "user" : user, # Ensure user is included here
              "timestamp" : timestamp # Add or remove as needed
          })

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the integration process of using Font Awesome with React?

After installing react-create-app using npm, I also added react-fontawesome. Now, I'm wondering how to include the css styles of fontawesome in my project? Here is a glimpse of my work space: https://i.stack.imgur.com/pM1g1.png ...

What could be causing the page to refresh every time a post or update is made using a mock REST API with JSON

I have been using Json-Server to mock API requests, but I'm facing an issue where the page reloads every time I fetch or update a post. I've tried searching for a solution, but haven't found one yet. Interestingly, even though I followed a ...

A guide to using select2.js to activate a selection based on a data attribute

I'm faced with the following html snippet: <div class='multiWrapper'> <select id="multi" class="js-dropdown-from-code"> <optgroup class='def-cursor' label='Code' data-city ...

Utilizing NodeJS, Express, and the Jade template engine to insert JSON data into

While trying to follow a tutorial on NodeJS, Express, Jade, and MongoDB, I ran into a frustrating issue. Despite reading through various forum threads and attempting the suggested solutions, I still can't seem to make the POST command work. Please di ...

Gradual disappearance of preloader as the page loads

I'm facing an issue with setting a gif as a website preloader. Despite trying different JavaScript solutions, the preloader remains visible even after the page has finished loading. $(window).on("load", function() { $(".loading").fadeOut("slow"); ...

The issue with logging out feature

Operating an ASP.NET Web application, I have a Logout feature implemented in JavaScript. However, my current code closes the browser upon Logout, which is not the desired behavior. Instead, I am looking to clear cookies/session and redirect the user to the ...

What are some visual aids and detailed breakdowns of Django's request handling process?

Can anyone provide a thorough explanation of the process that Django follows when handling requests, including how database connections are associated with requests (e.g. 1 to 1, 1 to N)? If not, I would be grateful for guidance on where in the code Djang ...

Issues with XFBML Like Buttons failing to load when generating numerous posts dynamically on a single page

On my webpage containing multiple posts, I am attempting to insert a Facebook LIKE button for each post. Utilizing XFBML code, I am trying to populate like buttons under every individual post with a unique URL, corresponding to the post URL. Here is the c ...

Error: The "checkAvailability" method is not available in the model object

When attempting to implement some functionality methods for my model, I encountered an issue where sending a request resulted in the following traceback: /home/nano/Dev/JS/OMI/node_modules/mongoose/lib/utils.js:413 throw err; ^ TypeE ...

Building XML using PHP with relatively extensive information stored in JavaScript

Similar Question: XML <-> JSON conversion in Javascript I have a substantial amount of data stored in JavaScript that I need to convert into an XML file on the PHP server. The process of transforming the data into a JSON object, sending it to PH ...

I am unable to make changes to my `<input type="file">` element

I've been struggling to modify this button, and even tried incorporating bootstrap javascript without success. Below is a snippet of the code I'm working with. Any guidance on how to achieve this would be highly appreciated. <html> < ...

Utilizing a universal search feature for enhanced filtering in react-table : Boosting efficiency with React and react-table

I am currently working on implementing a global search filter that can search for a specific key throughout the entire table. I have set up a change handler that triggers a callback function every time there is an input, which in turn searches for the spec ...

What steps are necessary to configure .eslintrc to identify the use of 'require'?

I recently started using ESLint and successfully integrated it with IntelliJ. Initially, ESLint did not recognize node out of the box. After consulting the documentation, I created a configuration file named .eslintrc at the project's root folder, sp ...

The Discord.js Avatar command does not support mentioning users

Everything seems to be working fine when I check my own avatar, but it doesn't work properly when I mention another user. Here's the code I'm using: client.on('message', message => { if (message.content === `${prefix}ava`) { ...

The conundrum with JQuery: My script refuses to run when a variable is defined

<script> $(document).foundation( let total = 1 $("button.test").click(function(){ if ($("p.change-me").text() === "OFF") { $("p.change-me").text("ON") total = total + 1 } ...

Automatically Refreshing on Vue.js: Embracing the Passage of Time

I want to display this clock on Vue. The clock should automatically update the time, but how can I make this code work in Vue? Is there a simple way to implement this in Vue without using (document.getElementBy...) function updateTime () { document.ge ...

How to position button components at the center in a NextJS application?

Incorporating a button within my nextjs page has been a challenge as I am striving to position it in the center of the page for optimal viewing on both PCs and mobile devices. Despite various attempts, the button remains fixed on the far left side of the p ...

Unusual activity discovered when using JavaScript addClass and removeClass methods

While experimenting with animate.css, I created a custom Javascript function to initiate animation events. This simple function, triggered by an onClick event on a button, is only three (or four) lines long, but encounters a perplexing error. The anim fu ...

Retrieving HTML content from a React array

One challenge I am facing is how to include HTML content inside a React array that I will use in the render method. To begin with, I start by creating my content using the following approach: let resultHtml = []; resultHtml.push(<p key="resultScore"&g ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...