python - 对于具有标准用户模型的具有外键的模型,RelatedObjectDoesNotExist

标签 python django

我有这个问题: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/

相关文章:

python - 后台django中的send_mass_mail

Python - 两个信号与内部 NaN 的互相关

python - 将 Django 与 virtualenv 一起使用,出现错误 ImportError : No module named 'django.core.servers.fastcgi'

python - django2 + python3 : TemplateDoesNotExist

python - 为 django 密码重置表单添加样式

django - 如何在 Django 中过滤连接模型?

python - Python制作命名空间包的方法

python - 创建一个堆栈和使用 for 循环遍历堆栈的迭代器

python - 如何在 python 中解析带有属性的 XML?

python - 为什么在这个类中采用这种方法?