【问题标题】:matching query does not exist. Django Error匹配的查询不存在。 Django 错误
【发布时间】:2021-12-26 08:48:57
【问题描述】:

这是我的项目代码,我只是得到了这个错误,我试图弄清楚但我不明白,

Django 错误:

DoesNotExist 在 /save_post/

配置文件匹配查询不存在。

views.py,第 75 行,在 save_post 中 form.authore = Profile.objects.get(user=request.user)

views.py

    @login_required
    def save_post(request):
        if request.method == "POST":
            form = Post(content=request.POST['content'])
            form.authore = Profile.objects.get(user=request.user)
            form.save()
        elif request.method == "PUT":
            data = json.loads(request.body)
            post_id = int(data["post_id"])
            new_content = data["new_content"]
            post = Post.objects.filter(id=post_id).first()
            if post.authore.user != request.user:
                return HttpResponse(status=401)
            post.content = new_content
            post.save()
            return JsonResponse({
                "result": True
            }, status=200)
        else:
            return JsonResponse({
                "error": "post not found"
            }, status=400)
        return index(request)

models.py

    class User(AbstractUser):
    pass


class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)


class Post(models.Model):
    content = models.TextField()
    timestamp = models.DateTimeField(default=timezone.now)
    authore = models.ForeignKey(Profile, on_delete=models.CASCADE)
    likes = models.PositiveIntegerField(default=0, blank=True, null=True)

    def serialize(self):
        return {
            "id": self.id,
            "content": self.content,
            "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"),
            "authore": self.authore.id,
            "username": self.authore.user.username,
            "likes": self.likes.count(),
        }

【问题讨论】:

  • 它说Profile matching query does not exist,这意味着给定的user没有Profile对象。
  • @Selcuk 有一个 Profile 类
  • 我尝试添加def serialize(self, user): return { "profile_id": self.user.id, "profile_username": self.user.username },但我还没有解决错误
  • 没有Profile 对象给定用户..._profile 数据库表中没有这样的行
  • @Selcuk 我不明白!我怎么没有配置文件对象我有配置文件和模型的 URL?

标签: python django django-models


【解决方案1】:

这似乎是正确的,但您已经使用的这个用户没有个人资料 所以这里是我的笔记:

你可以使用get_object_or_404 this if profile not found 将返回 not found

from django.shortcuts import  get_object_or_404
form.authore =  get_object_or_404(Profile, user=request.user)

当用户创建没有逻辑时,必须创建配置文件,所以它是逻辑用户没有配置文件

创建用户配置文件时最好使用 one_to_one 关系,因为每个用户只有一个配置文件,反之亦然

要使其正常工作,请参阅此处 https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

转到上一个链接中使用一对一链接扩展用户模型

字段执行本教程,用户配置文件将在用户创建时自动创建

【讨论】:

    猜你喜欢
    • 2013-07-22
    • 2015-04-20
    • 2021-07-26
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多