Django:查询堆叠内联对象 | /profile 处的 ValueError 无法查询 "Anthony_Jamez12":必须是 "Profile" 实例

Django: Querying a stacked inline object | ValueError at /profile Cannot query "Anthony_Jamez12": Must be "Profile" instance

我正在尝试制作 Instagram 克隆。所以我在这里要做的是查询用户上传的照片并将它们显示在前端。当我查询堆叠内联上传模型时,我可以获得要在前端显示的照片,但不是属于用户的照片(数据库中的所有照片都显示在前端)。我试图找出一种方法让所有照片都转到扩展用户模型,但我想不出办法做到这一点。基本上我正在尝试获取用户上传的图像,如果有人可以提供帮助,我们将不胜感激。

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
    first_name = models.CharField(max_length = 50, null = True, blank = True)
    last_name = models.CharField(max_length = 50, null = True, blank = True)
    phone = models.CharField(max_length = 50, null = True, blank = True)
    email = models.EmailField(max_length = 50, null = True, blank = True)
    bio = models.TextField(max_length = 300, null = True, blank = True)
    profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)
    #uploads = models.ForeignKey(Uploads, on_delete = models.CASCADE, default = None, null = True)

    def __str__(self):
        return f'{self.user.username} Profile'

class Uploads(models.Model):
    caption = models.CharField(max_length = 100, blank=True)
    image = models.FileField(upload_to = "img/%y", blank=True, null = True)
    profile = models.ForeignKey(Profile, on_delete = models.CASCADE, default = None, null = True)
    id = models.AutoField(primary_key = True, null = False)
    

    def __str__(self):
        return self.caption and str(self.image)

views.py

def profile(request):
    img = Uploads.objects.filter(profile_id = request.user)    #Here is my error and question
    #img = Uploads.objects.all()
    profile = Profile.objects.filter(user = request.user)
    context = {"profile": profile, "img": img}

    return render(request, "main/profile.html", context)

这里是模型的可视化表示,如果这有助于理解我想要得到的东西的话。

这样做 :-

def profile(request):
    img = Uploads.objects.filter(profile_id = request.user)
    #img = Uploads.objects.all()

# Changed this line
    profile = Profile.objects.filter(user = request.user.profile)
    context = {"profile": profile, "img": img}

    return render(request, "main/profile.html", context)
def profile(request):
    img = Uploads.objects.filter(profile_id = request.user)

您正在将用户类型对象传递给 profile_id,这需要 int 或者如果 profile 它需要一个 Profile 对象。 改成

profile = Profile.objects.filter(user = request.user)
img = Uploads.objects.filter(profile_id = profile.id)
context = {"profile": profile, "img": img}

img = Uploads.objects.filter(profile__user = request.user)
profile = Profile.objects.filter(user = request.user)

感谢 PrOgRaMmEr 和 ABHISHEK TIWARI,这是我需要改变的。

def profile(request):
    img = Uploads.objects.filter(profile_id = request.user.profile)
    profile = Profile.objects.filter(user = request.user)
    context = {"profile": profile, "img": img}

    return render(request, "main/profile.html", context)