javascript django没有收到正确的响应?在前面

qyswt5oh  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(136)

概述

当您按下“喜欢!”按钮时,会有通过服务器处理(创建或删除)反馈到前屏的处理。
创建时没有错误。反馈也很好。删除时出错,反馈不起作用。
错误的内容似乎是无法正确接收json。
创建过程和删除过程几乎是一样的,记录也是在数据库中注册和删除的,所以处理是完全一样的。
是什么引起的?看起来很简单,但是...

详情

第一节第一节第一节第一节第一次

# model
class Articles(models.Model):
    title = models.CharField(max_length=200)
    note = models.TextField()
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = ArticlesQuerySet.as_manager()

    @staticmethod
    def with_state(user_id: int) -> QuerySet:
        return Articles.objects.annotate(
                likes_cnt=Count('likes'),
                liked_by_me=Case(
                    When(id__in=Likes.objects.filter(user_id=user_id).values('articles_id'),
                         then=1),
                    default=0,
                    output_field=IntegerField()
                )
            )

class Likes(models.Model):
    articles = models.ForeignKey('Articles', on_delete=models.CASCADE)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['articles_id', 'user_id'],
                name='articles_user_unique'
            )
        ]
# views.py
class LikesCreateView(LoginRequiredMixin, CreateView):
    def post(self, request, *args, **kwargs):
        return_value = None
        try:
            Likes.objects.create(user_id=kwargs['user_id'], articles_id=kwargs['article_id'])
            article = Articles.with_state(kwargs['user_id']).get(pk=kwargs['article_id'])
            return_value = json.dumps({'likes_cnt': article.likes_cnt, 'liked_by_me': article.liked_by_me})
            print(f'LikesCreateView return_value[{type(return_value)}]: ', return_value)
        except User.DoesNotExist:
            logging.critical('There was an access from an unauthorized user account')
        except Articles.DoesNotExist:
            logging.critical('An unauthorized article was accessed')

        return HttpResponse(return_value, status=201)

class LikesDeleteView(LoginRequiredMixin, DeleteView):
    def post(self, request, *args, **kwargs):
        return_value = None
        try:
            Likes.objects.filter(user_id=kwargs['user_id'], articles_id=kwargs['article_id']).delete()
            article = Articles.with_state(kwargs['user_id']).get(pk=kwargs['article_id'])
            return_value = json.dumps({'likes_cnt': article.likes_cnt, 'liked_by_me': article.liked_by_me})
            # TODO: When creating, the front receives json correctly, but when it becomes delete, an accident occurs ...why?
            print(f'LikesDeleteView return_value[{type(return_value)}]: ', return_value)
        except User.DoesNotExist:
            logging.critical('There was an access from an unauthorized user account')
        except Articles.DoesNotExist:
            logging.critical('An unauthorized article was accessed')

        return HttpResponse(return_value, status=204)
<!-- index.html -->
<div class="col-sm">
  <h2>nice! function</h2>
  <h6>'like' function</h6>
  {% for article in articles %}
        :
    <button
        type="button"
        class="like_toggle btn btn-light"
        data-article-id="{{ article.id }}"
        data-liked-by-me="{{ article.liked_by_me }}"
    >nice!<span>({{ article.likes_cnt }})</span></button>
        :
  {% endfor %}
  <a href="{% url 'vnm:article_create' %}" class="btn btn-default btn-sm" role="button">post!</a>
</div>

  :

    <script lang="js">
        const likeToggles = document.getElementsByClassName('like_toggle');
        for (let i = 0; i < likeToggles.length; i++) {
            likeToggles[i].addEventListener('click', () => {
                const articleId = likeToggles[i].dataset.articleId
                const likedByMe = parseInt(likeToggles[i].dataset.likedByMe)
                console.log(`article_id: ${articleId} を User: {{ user.id }} ${likedByMe})`);
                const userId = {{ user.id }}
                if (!userId) {
                    location.href = myurl.login
                }

                const createOrDelete = likedByMe ? 'delete' : 'create'
                console.log(`createOrDelete: ${createOrDelete}`)
                fetch(`${myurl.base}likes/${createOrDelete}/${userId}/${articleId}/`, {
                    method: 'POST',
                    headers: {
                        "Content-Type": "application/json; charset=utf-8",
                        "X-CSRFToken": Cookies.get('csrftoken')
                    },
                    body: JSON.stringify({"status": "requested from javascript."})
                    }
                )
                .then(response => response.json())
                .then(json => {
                    console.log("return json is : ", json)
                    likeToggles[i].getElementsByTagName('span')[0].innerHTML = `(${json.likes_cnt})`
                    likeToggles[i].dataset.likedByMe = json.liked_by_me
                })
                .catch((error) => {
                    console.error('There has been a problem with your fetch operation:', error)
                })
            })
        }
    </script>
3pvhb19x

3pvhb19x1#

你在LikesDeleteView中返回status=204,这是
204 No Content: The server successfully processed the request, and is not returning any content.
https://en.m.wikipedia.org/wiki/List_of_HTTP_status_codes

return HttpResponse(return_value, status=204)

应该是像LikesCreateView中的200

相关问题