首页 > 解决方案 > 获取个人帖子ID

问题描述

我正在使用 Django 和 Vanilla JS 构建社交网络的副本。我想使用 fetch API 异步编辑帖子。

在 urls.py 我有一个 API 路由如下:

urlpatterns = [
...
path("edit/<int:post_id>", views.edit, name="edit"), 
...
]

在 models.py 中 Post 对象如下:

    class Post(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
        date_posted = models.DateTimeField(default=timezone.now)
        content = models.TextField()
        likes = models.IntegerField(default=0)

        def __str__(self):
            return f"{self.user.username} added a new post"

        def serialize(self):

            return {
             "id": self.id,
             "user": self.user,
             "date_posted": self.date_posted.strftime("%b %d %Y, %I:%M %p"),
             "content": self.content,
             "likes": self.likes}

在views.py中,编辑路径如下,目前:

@login_required
@csrf_exempt
def edit(request,post_id):
    try:
        post = Post.objects.get(user=request.user, pk=post_id)
    except Email.DoesNotExist:
        return JsonResponse({"error": "Post not found"}, status=404)

    if request.method == "GET":
        return JsonResponse(post.serialize())

根据分配规范,只有撰写帖子的用户才能对其进行编辑。在 index.html 中出现所有帖子和适用的编辑按钮。

...
{% for post in posts %}
<h3 class="border border-secondary rounded"><a href="{% url 'profile' post.user.id %}">{{ post.user.username }}</a>
</h3>
<hr>
<div class="border border-primary rounded mb-4">
    <div id="post-{{post.id}}">
        <p>{{ post.content }}</p>
        <p><small>{{ post.date_posted }}</small></p>
    </div>

    {% if user.username != post.user.username %}
    <button class="btn btn-sm btn-outline-secondary" id="like_btn">&heartsuit; <span class="ml-1">{{ post.likes }}
        </span></button>
    {% else %}
    <p> <small>{{ post.likes }} likes </small> </p>
    {% endif %}
    {% if post.user.id == request.user.id %}
    <button class="btn btn-primary btn-sm" id="edit_btn-{{post.id}}">Edit</button>
    {% endif %}
</div>
{% endfor %}
...

最后,我想添加通过 PUT 请求编辑帖子的功能。

script.js 包含该项目的所有 JS 函数。现在,我希望我的功能做的就是向控制台记录一条消息,说明我已单击要编辑的相应帖子

脚本.js

document.addEventListener('DOMContentLoaded', () => {
...
document.querySelector(`#edit_btn-${id}`).addEventListener('click', () => {
    edit();
  })
});
...
function edit(post) {
fetch(`/edit/${post.id}`)
.then((response) => response.json())
.then((post) => console.log(`Editing post ${post.id}...`));

在控制台中,当我单击编辑按钮时收到以下消息:

Uncaught ReferenceError: id is not defined
at HTMLDocument.<anonymous> (script.js:10)

script.js 中的第 10 行是我进行函数调用的位置。

我对可能导致此错误的原因感到困惑。任何帮助将不胜感激。谢谢你。

标签: javascriptpythondjango-views

解决方案


您需要使用更好的方法来获取 id。

例如,在您的 for 循环中,您可以使用

{% if post.user.id == request.user.id %}
<button class="btn btn-primary btn-sm" onclick="edit({{post.id}})">Edit</button>
{% endif %}

在您的 js 中,您可以使用它

function edit(id) {
    fetch(`/edit/${id}`)
     .then((response) => response.json())
     .then((post) => console.log(`Editing post ${id}...`));
}

推荐阅读