0

In my Project, I have an application called Score where users can upload Images, I am trying to add the Like functionality to these posts, using Ajax and Jquery to prevent the images from being refreshed.

The like option is working fine but still must be refreshed so that the updates appear. In the console I am getting

jquery.min.js:2 POST http://127.0.0.1:8000/like/ 404 (Not Found)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ (index):241
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2

Although it is supoosed to be http://127.0.0.1:8000/score/like/

My question is how to handle this error?

Worth to mention that I have another application that I am using the same Like Functionality but the application is used for completely different purposes.

Models.py

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    designer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post")
    date_posted = models.DateTimeField(default=timezone.now)
    likes = models.ManyToManyField(
        User, related_name='liked_designs', blank=True)
    num_likes = models.IntegerField(default=0, verbose_name='No. of Likes')

LIKE_CHOICES = (
    ('Like', 'Like'),
    ('Unlike', 'Unlike')
)

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="liked_designs_users")
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES,
                             default='Like', max_length=8)

Here is the post detail views.py

class PostDetailView(ObjectViewMixin, DetailView):
    model = Post
    template_name = "score/post_detail.html"  # <app>/<model>_<viewtype>.html

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        comments = Comment.objects.filter(post=post).order_by('-id')
        total_likes = post.total_likes()
        liked = False

        if post.likes.filter(id=self.request.user.id).exists():
            liked = True

        context["total_likes"] = total_likes
        context["liked"] = liked
        return context

Here are the likes view.py

def Like_View(request):
    # post = get_object_or_404(Post, id=request.POST.get('post_id'))
    post = get_object_or_404(Post, id=request.POST.get('id'))
    liked = False
    current_likes = post.num_likes
    user = request.user
    if post.designer.id == request.user.id:
        messages.warning(request, 'You can not like you own Post')

    else:

        if post.likes.filter(id=request.user.id).exists():
            post.likes.remove(request.user)
            liked = False
            current_likes = current_likes - 1

        else:
            post.likes.add(request.user)
            liked = True
            current_likes = current_likes + 1

        post.num_likes = current_likes
        post.save()

    context = {
        'total_likes': post.total_likes,
        'liked': liked,
        'post': post,
    }
    if request.is_ajax:
        html = render_to_string('score/like_section.html', context, request=request)
        return JsonResponse({'form': html})

Here is the main project url

from score.views import Like_View

    path('score/like/', Like_View, name='design_like_post'),

Here is the post-detail.html:

            <div id="like-section-design">
            {% include 'score/like_section.html' %}
            </div>

Here is the score/like_section.html:

    <form class="mt-0" action="{% url 'design_like_post' %}" method='post'>
        {% csrf_token %}
            {% if liked %}
                  <button type='submit' id="like" name='post_id' value='{{post.id}}' style="...">
                    Like <i class="far fa-thumbs-up"></i>
                  </button>
            {% else %}
                  <button type='submit' id="like" name='post_id' value='{{post.id}}' style="...">
                     Like <i class="far fa-thumbs-up"></i>
                  </button>
            {% endif  %}
    </form>

Here is the scripts:

    <script type="text/javascript">
        $(document).ready(function(event){
            $(document).on('click','#like', function(event){
                event.preventDefault();
                var pk= $(this).attr('value');
                $.ajax({
                    type:'POST',
                    url:'{% url "design_like_post" %}',
                    data:{'id': pk, 'csrfmiddlewaretoken':'{{csrf_token}}'},
                    dataType:'json',
                    success:function(response){
                        $('#like-section-design').html(response['form'])
                        console.log($('#like-section-design').html(response['form']));
                    },
                    error:function(rs, e){
                        console.log(rs.responseText);
                    },
                });
            });
        });
    </script>

Thank you for encouraging me to learn from my mistakes

A_K
  • 731
  • 3
  • 15
  • 40
  • 2
    Does it work if you change to `url:'/score/like/',` in the `$.ajax`? – charlietfl Dec 14 '20 at 01:56
  • Are you sure that you have only ***one*** URL named `design_like_post` in your project? – JPG Dec 14 '20 at 02:10
  • Similar questions: https://stackoverflow.com/questions/24370186/jquery-ajax-returning-404-not-found https://stackoverflow.com/questions/36627337/post-http-localhost3000-404-not-found https://stackoverflow.com/questions/56902832/post-http-localhost3000-api-signup-404-not-found – react_or_angluar Dec 14 '20 at 02:11
  • @ArakkalAbu yes I have only one URL named `design_like_post` but there is another URL with a similar purpose for the like function for another application `path('like/', views.LikeView, name='like_post'),` – A_K Dec 14 '20 at 02:15
  • @ArakkalAbu this URL belong to `from blog import views` – A_K Dec 14 '20 at 02:28
  • @charlietfl could you explain more how to do that ? – A_K Dec 14 '20 at 04:23
  • Just comment out what you have now and replace with that string – charlietfl Dec 14 '20 at 05:31

0 Answers0