django 字段“id”需要一个数字,但得到了“”,上述异常(基数为10的int()的文字无效:“”)是导致以下异常的直接原因

l7mqbcuq  于 2023-03-31  发布在  Go
关注(0)|答案(1)|浏览(153)

我将学习Python,我试图做视频课程,但一切都为他们工作,但我得到这个错误,我想写喜欢使用JavaScript。但它给了我一个错误在这一点上:post_obj = Post.objects.get(id=post_id)
models.py

title = models.CharField(max_length=222, verbose_name='Заголовок')
    text = models.TextField(blank=True, verbose_name='Текст')
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    views = models.ManyToManyField(IpModel, related_name="post_views", blank=True)

    def total_views(self):
        return self.views.count()

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('new_detail', kwargs={'pk': self.pk})

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

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES, max_length=8)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user}-{self.post}-{self.value}"

views.py

def like_unlike_post(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post_id)
        user = Post.objects.get(user=user)

        if user in post_obj.liked.all():
            post_obj.liked.remove(user)
        else:
            post_obj.liked.add(user)

        like, created = Like.objects.get_or_create(user=user, post_id=post_id)

        if not created:
            if like.value=='Like':
                like.value='Unlike'
            else:
                like.value='Like'
        else:
            like.value='Like'

            post_obj.save()
            like.save()

    return redirect('like_button:main-post-view')

urls.py

urlpatterns = [
    path('', index, name='index'),
    path('liked/', like_unlike_post, name='like-post-view'),

超文本标记语言

<div class="content">
                <p> {{ obj.content }} </p>
                <div class="right floated">
                    <form action="{% url 'like_button:like-post-view' %}" method="POST" class='like-form' id='{{obj.id}}'>
                        {% csrf_token %}
                        <input type="hidden" name="post_id" value={{obj.id}}>

                            <button type="submit" class="ui button like-btn{{obj.id}}">
                                ❤
                                {% if profile not in obj.liked.all %}
                                    Like
                                {% else %}
                                    Unlike
                                {% endif %}
                            </button>
                            <div class="ui grid">
                                <div class="column">
                                    <div class="like-count{{obj.id}}"> {{obj.num_likes}} </div>
                                </div>
                                <div class="column">
                                    likes
                                </div>
                            </div>
                    </form>
                </div>

    <script>
        $( document ).ready(function() {
            let display = false
            $(".cmt_btn").click(function () {
                if (display===false) {
                    $(this).next(".comment-box").show("slow");
                    display=true
                } else {
                    $(this).next(".comment-box").hide("slow");
                    display=false
                }
            });

            $('.like-form').submit(function(e){
                e.preventDefault()

                const post_id = $(this).attr('id')

                const likeText = $(`.like-btn${post_id}`).text()
                const trim = $.trim(likeText)

                const url = $(this).attr('action')

                let res;
                const likes = $(`.like-count${post_id}`).text()
                const trimCount = parseInt(likes)

                $.ajax({
                    type: 'POST',
                    url: url,
                    data: {
                        'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
                        'post_id':post_id,
                    },
                    success: function(response) {
                        if(trim === 'Unlike') {
                            $(`.like-btn${post_id}`).text('Like')
                            res = trimCount - 1
                        } else {
                            $(`.like-btn${post_id}`).text('Unlike')
                            res = trimCount + 1
                        }

                        $(`.like-count${post_id}`).text(res)
                    },
                    error: function(response) {
                        console.log('error', response)
                    }
                })

            })
        });
    </script>

我尝试将post_id = request.POST.get('post_id')更改为post_id = request.POST.get('id')
错误:Traceback切换到复制粘贴视图

D:\Projects\site_news\venv\Lib\site-packages\django\db\models\fields\__init__.py, line 2018, in get_prep_value

                return int(value)

     …
Local vars
The above exception (invalid literal for int() with base 10: '') was the direct cause of the following exception:
D:\Projects\site_news\venv\Lib\site-packages\django\core\handlers\exception.py, line 56, in inner

                    response = get_response(request)

     …
Local vars
D:\Projects\site_news\venv\Lib\site-packages\django\core\handlers\base.py, line 197, in _get_response

                    response = wrapped_callback(request, *callback_args, **callback_kwargs)

     …
Local vars
D:\Projects\site_news\main\views.py, line 360, in like_unlike_post

            post_obj = Post.objects.get(id=post_id)
tf7tbtn2

tf7tbtn21#

在POST请求中,post_id似乎是一个空字符串:

post_id = request.POST.get('post_id')
post_obj = Post.objects.get(id=post_id

请检查 AJAX 调用端的post_id值

相关问题