【问题标题】:Obtaining individual post id获取个人帖子ID
【发布时间】:2021-06-15 06:51:02
【问题描述】:

我正在使用 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 函数。现在,我希望我的功能做的就是在控制台中记录一条消息,说明我已经点击了要编辑的相应帖子

script.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 行是我调用函数时的位置。

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

【问题讨论】:

    标签: javascript python django-views


    【解决方案1】:

    你需要用更好的方式来获取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}...`));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 2010-12-04
      • 2017-04-23
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      相关资源
      最近更新 更多