Django社交应用开发:Profile匹配查询不存在及图片报错求助
Django社交应用Profile不存在错误的排查与解决
问题描述
跟着教程开发Django社交应用,严格按步骤操作仍卡了好几天:
- 打开个人资料设置页时触发
DoesNotExist错误,报错指向代码user_profile = Profile.objects.get(user=request.user) - 偶尔会出现
profile_img找不到的错误,注释models.py里的profile_img字段后,报错变回“profile匹配查询不存在” - 注释掉获取Profile对象的代码后,设置页面能正常访问
相关代码
原设置页面views.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, 'settings.html', {'user_profile': user_profile})
Profile模型(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')
注释Profile获取后的views.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', )
目录结构说明
项目根目录包含core、media、templates等文件夹,core目录下有views.py、models.py等核心文件,templates目录存放settings.html等模板文件。
问题分析与解决办法
核心原因
当前登录的用户在数据库中没有对应的Profile记录,get()方法找不到匹配项时直接抛出DoesNotExist异常,这是你遇到的主要问题。
具体解决方案
用户创建时自动生成Profile
用Django信号实现用户注册后自动创建Profile,避免手动遗漏。在models.py末尾添加:from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance, id_user=instance.id) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save()然后在core/apps.py中注册信号:
from django.apps import AppConfig class CoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'core' def ready(self): import core.models # 加载信号所在的模块修复views.py的异常处理逻辑
不要直接用get(),改用异常捕获或者get_object_or_404,同时跳转到Profile创建页面(需提前实现该视图):from django.shortcuts import redirect, get_object_or_404 @login_required(login_url='signin') def settings(request): try: user_profile = Profile.objects.get(user=request.user) return render(request, 'settings.html', {'user_profile': user_profile}) except Profile.DoesNotExist: return redirect('create_profile') # 替换为你的创建Profile路由名解决profile_img找不到的问题
- 确保
blank_profile_image.jpeg放在项目根目录的media/文件夹下 - 检查settings.py的媒体配置:
MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' - 在项目根urls.py中添加媒体路由:
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # 你的其他路由配置 ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 确保
补全已有用户的Profile记录
对于已经注册但没有Profile的用户,在Django shell中执行以下命令批量创建:python manage.py shell然后输入:
from django.contrib.auth.models import User from core.models import Profile for user in User.objects.all(): Profile.objects.get_or_create(user=user, id_user=user.id)
内容的提问来源于stack exchange,提问作者blazingIce269
相关产品推荐
相关产品推荐

