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

rjee0c15  于 2023-03-31  发布在  Go
关注(0)|答案(2)|浏览(123)

我正在使用django构建社交媒体应用程序的教程。我有这个bug,尽管完全按照教程进行,但它让我卡住了好几天。每当我试图打开个人资料的设置页面时,我都会得到doesNotExist错误。
错误似乎来自这里“user_profile = Profile.objects.get(user=request.user)“这是我的设置页面的视图

@login_required(login_url='signin')
def settings(request):
    # Check if logged in user has profile, if not redirect to create profile
    user_profile = Profile.objects.get(user=request.user)
    return render(request, 'settings.html', {'user_profile': user_profile})

有时我会得到一个关于profile_img未被找到的错误。虽然我在这里寻求帮助时无法让它重复。但是当我在www.example.com中注解掉profile_img行modles.py,错误又变回了'profile not matching query'
这是我的models.py

class Profile(models.Model):
    objects = models.Manager()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id_user = models.IntegerField()
    bio = models.TextField(blank=True)
    location = models.CharField(max_length=150, blank=True)
    profile_img = models.ImageField(upload_to='profile_images', default='blank_profile_image.jpeg')

但是,删除指向我的www.example.com的链接modles.py似乎可以访问设置页面。

@login_required(login_url='signin')
def settings(request):
    # Check if logged in user has profile, if not redirect to create profile
    #user_profile = Profile.objects.get(user=request.user)
    return render(request, 'core/settings.html', )

这是我的文件目录结构directory structure

knpiaxh1

knpiaxh11#

此错误是因为您没有Profile模型中当前用户的数据。解决方法应该是检查数据是否存在或执行其他操作,例如-

@login_required(login_url='signin')
def settings(request):
    # Check if logged in user has profile, if not redirect to create profile
    user_profile = Profile.objects.filter(user=request.user)
    if user_profile.exists()
        return render(request, 'settings.html', {'user_profile': user_profile[0]})
    else:
        return redirect("/") # or wherever you want to
mnowg1ta

mnowg1ta2#

您登录的用户是否存在配置文件对象?
您可以通过执行以下操作快速调试它:

@login_required(login_url='signin')
def settings(request):
    print('User Profile QS:', Profile.objects.filter(user=request.user))
    # Check if logged in user has profile, if not redirect to create profile
    # user_profile = Profile.objects.get(user=request.user)
    return render(request, 'core/settings.html', )

看看终端输出,如果它是空的,它很可能是,只要创建一个,它应该工作。
根据您的评论Check if logged in user has profile, if not redirect to create profile
最好重构视图,使其更像:

@login_required(login_url='signin')
def settings(request):
    # Check if logged in user has profile, if not redirect to create profile
    user_profile = Profile.objects.filter(user=request.user).first()

    if user_profile is None:
      from django.shortcuts import redirect
      return redirect('/my_redirect_url/')

    return render(request, 'settings.html', {'user_profile': user_profile})

相关问题