我有这个问题:RelatedObjectDoesNotExist
我将 UserProfile 添加到我的模型中(目前只有头像要添加到用户模型中。
不强制添加图片。所以有些 userProfile 为空。问题是当我编辑用户表单和配置文件用户表单时。我有一个错误: 相关对象不存在,位于/accounts/user_edit/ 用户没有个人资料。
我尝试添加一个 try: except 在 View 中,但似乎不起作用
模型.Py:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # il s'agit d'ajouter des infos au modele User
# add any additional attributes needed
avatar = models.ImageField(upload_to='profile_pics', blank=True) # avatar of the user in director profile_pics
def __str__(self):
return self.user.email
View .py:
@login_required(login_url='account/sign_up.html')
def user_edit(request):
# Get info from "both" forms
# It appears as one form to the user on the .html page
user_form = UserFormEdit(instance=request.user)
profile_form = UserProfileForm(instance=request.user.profile)
# Check to see both forms are valid
if user_form.is_valid() and profile_form.is_valid():
# Prepare Save User Form to Database
user = user_form.save()
profile = profile_form.save(commit=False)
# Check if they provided a profile picture
if 'profile_pic' in request.FILES:
print('found it')
# If yes, then grab it from the POST form reply
profile.profile_pic = request.FILES['profile_pic']
profile.save()
messages.success(request, 'User updated')
return render(request, 'account/user_edit.html',
{'user_form': user_form,
'profile_form': profile_form}
)
profile_form = UserProfileForm(instance=request.user.profile) 出错
因为请求为空......
我希望能够在创建用户后添加或编辑用户配置文件信息。因此,如果它尚不存在,它应该渲染一个空的 UserProfileForm ,或者如果存在,则渲染实例 user.profile 数据
感谢您的帮助
最佳答案
您可以检查配置文件是否存在,如果不存在则使用新实例。
try:
profile = request.user.profile
except UserProfile.DoesNotExist:
profile = UserProfile(user=request.user)
profile_form = UserProfileForm(instance=profile)
关于python - 对于具有标准用户模型的具有外键的模型,RelatedObjectDoesNotExist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027600/