You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行python manage.py runserver后项目运行,Admin面板部分选项触发DoesNotExist错误

解决Django中UserProfile matching query does not exist错误

问题原因

当前登录用户对应的UserProfile记录不存在,视图代码中直接使用get()方法查询,而get()在无匹配结果时会抛出DoesNotExist异常。

解决方案

1. 修复视图代码,处理Profile不存在的情况

修改account/views.py中的profile视图,捕获异常或跳转至创建页面:

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import UserProfile

@login_required
def profile(request):
    try:
        profile = UserProfile.objects.get(id=request.user.id)
    except UserProfile.DoesNotExist:
        # 重定向到Profile创建页面,需提前定义对应视图和URL
        return redirect('create_profile')
    return render(request, 'account/profile.html', {'profile': profile})

若缺少创建Profile的视图,补充如下代码:

@login_required
def create_profile(request):
    if request.method == 'POST':
        # 根据实际模型字段处理表单数据
        profile = UserProfile.objects.create(user=request.user)
        # 补充其他字段赋值逻辑
        profile.save()
        return redirect('profile')
    return render(request, 'account/create_profile.html')

2. 为现有用户批量生成Profile记录

通过Django Shell为已有用户批量创建对应Profile:

python manage.py shell

在Shell中执行:

from django.contrib.auth.models import User
from account.models import UserProfile

for user in User.objects.all():
    # get_or_create避免重复创建
    UserProfile.objects.get_or_create(id=user.id, user=user)

3. 用信号自动为新用户创建Profile

在account/models.py中添加post_save信号,确保新创建的User自动生成Profile:

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import UserProfile

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(id=instance.id, user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.userprofile.save()

确保UserProfile模型与User为一对一关联:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # 其他自定义字段...

内容的提问来源于stack exchange,提问作者Md. Mohai Minul Islam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:45:06