DoesNotExistat/settings:配置文件匹配查询不存在


@login_required(login_url='signin')
def settings(request):
user_profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
if request.FILES.get('image') == None:
image = user_profile.profileimg
bio = request.POST['bio']
location = request.POST['location']
user_profile.profileimg = image
user_profile.bio = bio
user_profile.location = location
user_profile.save()
if request.FILES.get('image') !=None:
image = request.FILES.get('image')
bio = request.POST['bio']
location = request.POST['location']
user_profile.profileimg = image
user_profile.bio = bio
user_profile.location = location
user_profile.save()

返回render(请求,'setting.html',{'user_profile':user_profile}(



user_profile = Profile.objects.get(user_profile=request.user)

你好,我正在尝试为我正在创建的社交应用程序运行此代码,但我无法继续,因为我一直收到错误消息,无法继续。我需要帮助,谢谢。

错误很明显:发出请求的用户没有与其关联的Profile

您应该处理配置文件不存在的情况。

try:
user_profile = Profile.objects.get(user=request.user)
except:
# handle user_profile creation here
user_profile = Profile(user=request.user, ...)

或者使用https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get-或创建

或者有一个post_save信号,如果它还不存在,它会自动为每个用户创建一个Profile。

最新更新