0

I have been working really hard with lots of investigation trying to implement a follow system in my django project. When I finished with my code, everytime I press the "follow" button, the server returns this error Failed to load resource: the server responded with a status of 500 (Internal Server Error) What can I do to stop having this error? I think the problem is on the javascript of my code.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    connection = models.CharField(max_length = 100, blank=True)
    follower = models.IntegerField(default=0)
    following = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.user.username} Profile'

class Following(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    followed = models.ManyToManyField(User, related_name="followed")
    follower = models.ManyToManyField(User, related_name="follower")

    @classmethod
    def follow(cls, user, another_account):
        obj, create = cls.objects.get_or_create(user = user)
        obj.followed.add(another_account)
        print("followed")

    @classmethod
    def unfollow(cls, user, another_account):
        obj, create = cls.objects.get_or_create(user = user)
        obj.followed.remove(another_account)
        print("unfollowed")

    def __str__(self):
        return f'{self.user.username} Profile'

views.py

def follow(request, username):
    main_user = request.user
    to_follow = User.objects.get(username=username)
    following = Following.objects.filter(user = main_user, followed = to_follow)
    is_following = True if following else False 


    if is_following:
        Following.unfollow(main_user, to_follow)
        is_following = False
    else:
        Following.follow(main_user, to_follow)
        is_following = True
    resp = {
        'following': is_following,
    }
    response = json.dumps(resp)
    return HttpResponse(response, content_type="application/json")

def profile(request, username):
    profile, created = Profile.objects.get_or_create(user=request.user)
    user = User.objects.filter(username=username)
    if user:
        post_owner = get_object_or_404(User, username=username)
        user = user[0]
        is_following = Following.objects.filter(user=request.user, followed=user)
        following_obj = Following.objects.get(user=user)
        follower = following_obj.follower.count()
        following = following_obj.followed.count()

    else:
        post_owner = request.user
        
    args1 = {
        'user_obj':user,
        'post_owner': post_owner,
        'follower': follower,
        'following': following,
        'connection': is_following,
    }
    return render(request, 'profile.html', args1)

profile.html

<head>
    <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
</head>
<body>
{% if connection %}
    <a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' user_obj.username %}">Unfollow</a>
{% elif not connection %}
    <a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' user_obj.username %}">Follow</a>
{% endif %}
<script type="text/javascript">
    $("#follow").click(function(e){
        e.preventDefault();
        var href = this.href;
        $.ajax({
            url : href,
            success : function(response){
                if(response["following"]){
                    $("#follow").html("Unfollow");
                }
                else{
                    $("#follow").html("Follow");
                }
            }
        })
    })
</script>
</body>

enter image description here

Juan Martin Zabala
  • 743
  • 2
  • 9
  • 29
  • Not likely. to be the js, 500s are as described "Internal _Server_ Errors". Look in the browser console for js errors. – Ben Jul 22 '20 at 21:41
  • @Ben the browser console shows the error, let me add a picture – Juan Martin Zabala Jul 22 '20 at 21:42
  • It would be helpful to see what your Following class looks like. – Ben Jul 22 '20 at 21:43
  • @Ben I added the pictor and the following model;) Also I have a signals.py file that is related to this follow system, should I add that? – Juan Martin Zabala Jul 22 '20 at 21:46
  • Are you certain your request on the `follow` view has a user? – Ben Jul 22 '20 at 22:04
  • Also, you should return a JsonResponse instead of a HTTPResponse from your `follow()` view. – Ben Jul 22 '20 at 22:07
  • @Ben I think there is no user on the follow view because I am getting also a `User matching query does not exist` error which triggers this two lines on follow view `Following.unfollow(main_user, to_follow)` `obj.followed.remove(another_account) ` and this line on the signals.py file`logged_user = User.objects.get(username = instance)` –  Jul 22 '20 at 22:15
  • @Ben How can the follow view have a user?? – Juan Martin Zabala Jul 22 '20 at 22:20
  • Your follow view doesn't have a user because it's a simple ajax request, without logged-in user specific info. To pass that info through, you'll likely want to set it up as a Post request: https://api.jquery.com/jquery.post/ that way you can more securely pass the user's info. There are some examples here: https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request – Ben Jul 22 '20 at 22:59
  • @Ben So I would have to add type = “POST” to the JavaScript and then add it request.method == Post: to the follow view right? Sorry I am on the phone and very new to JavaScript. –  Jul 22 '20 at 23:33
  • @Ben I tried what I said I was going to do but it didnt worked, it returned a 403 error. Can you help me with an answer please? – Juan Martin Zabala Jul 23 '20 at 01:05

0 Answers0