Why is the 'follow' button in Django not functioning properly?

I am currently working on a project using Django 2.2 and PostgreSql. The goal of the app is to allow users to follow their neighbors. The 'Follow' button should increase the number of followers, while the 'Unfollow' button should decrease the count. However, I am facing an issue where the 'Follow' button is not functioning as expected. How can I resolve this issue?

following/models.py

class Following(models.Model):
    follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='fallower', null=True)
    followed = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='fallowing')

following/views.py

def user_follow_unfollow(request):
    response = sub_user_follow_unfollow(request)
    data = response.get('data')
    followed = response.get('followed')
    numbers_followed_and_follower= Following.user_followed_and_follower(followed)
    context = {'user': followed, 'followers': numbers_followed_and_follower['followers'],
           'followeds': numbers_followed_and_follower['followeds']}
    html = render_to_string('following/following_partion.html', context=context, request=request)
    data.update({'html': html})
    return JsonResponse(data=data)

def sub_user_follow_unfollow(request):
    if not request.is_ajax():
        return HttpResponseBadRequest()

    data = {'follow status': True, 'html': '', 'is_valid': True, 'msg': '<b>Unfollow</b>'}
    follower_username = request.GET.get('follower_username', None)
    followed_username = request.GET.get('followed_username', None)

    follower = get_object_or_404(User, username=follower_username)
    followed = get_object_or_404(User, username=followed_username)

    does_follow_the_user= Following.user_does_follow_the_user(follower=follower, followed=followed)

    if not does_follow_the_user:
        Following.user_follow(follower=follower, followed=followed)
    else:
        Following.user_unfollow(followed=followed, follower=follower)
        data.update({'msg': '<b>Follow</b>', 'follow_status': False})
    return {'data': data, 'followed': followed}

templates.following_partion.html

      {% if request.neighbor_detail != user %}
          <div>
              <button followed='{{ neighbor_detail.username }}' followed='{{ request.neighbor_detail.username }}'
                      url="{% url 'following:user_follow_and_unfollow' %}" id="follow_unfollow_button"
                      class="btn btn-lg btn-success">
                  {% if does_follow_the_user%}
                      <b>Unfollow</b>
                  {% else %}
                      <b>Follow</b>
                  {% endif %}
              </button>
          </div>
      {% endif %}


   <div class="followers col-lg-offset-3 col-md-3 col-md-offset-3 col-lg-3 text-center">
<span><b>followers</b></span>
<button url="{% url 'following:fallowed-or-fallowers-list' 'fallowers' %}" follow_type="followers"
        username="{{ neighbor_detail.username }}" class="follow_button btn-block btn btn-primary">
    {{ followers}}
</button>

  <div class="followeds col-lg-3 col-md-3 text-center">
<span><b>Followeds</b></span>
<button url="{% url 'following:followed-or-followers-list' 'followed' %}" follow_type="followed"
        username="{{ neighbor_detail.username }}" class="follow_button btn-block btn btn-success">
    {{ followeds}}
</button>

my script

 <script>
 $("#follow_unfollow_button").click(function () {
               var $this = $(this);
               var $url = $this.attr('url');
               var $takip_eden = $this.attr('follower');
               var $takip_edilen = $this.attr('followed');
               var data = {follower_username: $follower, followed_username: $followed};
               $.ajax({
                   url: $url,
                   type: 'GET',
                   dataType: 'json',
                   data: data,
                   success: function (data) {
                       if (data.is_valid) {
                           $this.html(data.msg);
                           $("#user_following").html(data.html)
                       }
                   }
               })
           });
</script>

Answer №1

We regret to inform you that we are unable to assist you at this time due to several missing components. Nevertheless, resolving the issue should not be too complicated to troubleshoot. Here are a few key areas to focus on:

  1. Examine the HTTP request (XHR request) in your browser developer tools to determine which parameters are being sent.
  2. In your Python debugger, inspect the values of request.GET, data, and numbers_followed_and_follower. Understanding these values is crucial for identifying any potential errors.
  3. If the problem persists, set a breakpoint in your view using your Python IDE and carefully trace through your code line by line to analyze the outcomes. Utilizing an IDE with a robust debugger is highly recommended.
  4. Review the HTTP response to your AJAX request in the browser developer tools to understand what data is being returned.

Analyze each of your variables systematically to pinpoint the source of the problem.

Recommendations

  • Consider utilizing POST instead of GET in your AJAX call, especially when making database modifications.
  • Implement a ManyToManyField to manage follower relations, representing connections between two users as follows:

    follows = models.ManyToManyField("self", symmetrical=False, related_name="followers")
    

    By specifying symmetrical=False, Django distinguishes between the two directions of the relationship. To create or remove relationships within your view, and to view existing relationships, utilize the following commands:

    user.follows.add(other_user)  # user follows other_user
    user.follows.remove(other_user)  # user unfollows other_user
    user.followers.all()  # list of followers
    user.followers.count()  # number of followers
    

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 best way to transform an array of key–value objects into an array of objects containing just one property?

I am working with an array of objects that looks like this: [ { "key": "fruit", "value": "apple" }, { "key": "color", "value": "red" }, { "key": "location& ...

How can a function in one React component be invoked from another component?

Currently in my React project's App.js, I am calling the this.searchVenues() function in my return statement. It works, but the implementation is messy and I know there must be a more efficient way to achieve this. The searchVenues() function is locat ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Is there a way to identify the exact moment when a function is loaded?

I am currently utilizing the Google Maps JavaScript v3 API and encountering some delays in loading. It seems that certain functions are available before others. I'm specifically interested in knowing when the getBounds function is ready for use from ...

Sending complicated JSON objects through AJAX to a MVC2 controller

Although this question has appeared in a similar form before, I am currently facing a dilemma.... I am encountering the common issue of passing a complex JSON type to MVC2. The problem lies in the fact that, as shown in the code below, while I am able to s ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Is it possible to modify the icon of a date picker in Ant Design?

Is it feasible to switch the icon of a date picker from the ant design framework to a material ui icon? https://i.sstatic.net/blbH1.png Material UI icon for reference: https://i.sstatic.net/zpJsZ.png ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Server-side form validation in Node.js with client-side feedback handling

Express-form is a validation plugin for node.js/express that offers powerful features. However, the examples and documentation currently only show server-side responses (console.log), which may not be very user-friendly. Two possible solutions come to min ...

Displaying an image in .png format from an ajax response - a simple guide

I am trying to send an image in bytes using ajax response.getOutputStream().write(encoder.pngEncode()) in my Servlet class. Is there a way to display the image at runtime in my JSP using the ajax response? Can someone help me with this problem? In my Serv ...

Content missing from the webpage

I can't figure out why my database entries are not showing up on my page, even though the topic names are displayed correctly. Currently, I am attempting to display entries from my database on a specific page. While the Topic name from the database i ...

The new and improved Vue 3 computed feature in the Composition API

The temporary object appears as: tmp : { k1: { k2 : { k3 : [abc, def] } } To access k3 in the setup, it should be: tmp.value.k1.k2.k3[0 or 1]. I am looking to change its name to something like - k3_arr = tmp.value.k1.k2.k3; Within my Vue single componen ...

Can a JavaScript (NodeJS) command or function be executed without halting the program in case of an error?

Is there a way in JavaScript to execute a function without interrupting the program if an error occurs? player.play('./sounds/throughQueue.mp3', function(err){ // let the program continue execution even if ther ...

Events triggered when a Jquery checkbox is toggled between checked and unchecked

I have written some HTML code that utilizes jQuery to manage checkboxes. <tr> <td> <div class="checkbox"> <label><input type="checkbox" id="checkbox2"></label> </div> </td> & ...

The error message "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client" indicates that

Continuously encountering an error related to a res.redirect despite adding a 'return' in the function to end the middleware. The error persists despite attempting to resolve it in this manner. Below is the function in question: app.post('/ ...

The scope chain in Chrome v71 connects the anchor tag to the inner img tag

Ever since updating to Chrome v71, I've noticed a strange issue with the scope of an anchor tag that contains an img tag inside. Take a look at this snippet: <a href="#none" onclick="debugger;complete();"> <img src="https://clickmeuk.net/w ...

Struggling to make MVC jQuery Ajax Post function with dynamically generated data, hardcoded values seem to be the only solution

I have a simple controller that receives a post request.. [HttpPost] public ActionResult Submit(string postCost) { //Perform necessary actions before redirecting... return Json(new { result = "Redirect", url = Url.Action("Inde ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Access Django template variables while using ng-repeat

My scenario involves a list of items, each accompanied by a checkbox. Users have the ability to select certain items and then perform a search for additional items by entering a query and clicking the "Search" button, triggering a POST request. It's c ...

NodeJS/ExpressJS API exposure

Currently, I am developing a website using Express and implementing route handling with the help of express router. The routes I have set up so far include registration, login, upload, and more. One particular route, upload, requires files to be uploaded ...