【问题标题】:AttributeError: 'bool' object has no attributeAttributeError: 'bool' 对象没有属性
【发布时间】:2018-05-15 23:17:21
【问题描述】:

我正在处理一个 Django 项目,基本上我已经编写了一个存储用户详细信息的模型。他们在注册后完成了此配置文件,并且我在用户模型中有一个布尔值,表明他们是否已完成此自定义配置文件,以便我可以在模板中进行更改。

当第二个个人资料页面的表单被提交时,我希望它将 Bool 从 False 更新为 True,但我收到了错误:

'bool' object has no attribute 'has_created_artist_profile'

见下面的代码:

views.py

def ArtistEditView(request):
    artist = Artist.objects.get(user=request.user)
    current_artist = request.user
    artist_status = current_artist.has_created_artist_profile

    if request.method == 'POST':
        form = ArtistForm(request.POST, request.FILES, instance=artist)
        if form.is_valid():
            artist_status.has_created_artist_profile = True
            artist_status.save()
            form.save()
            return redirect(reverse('artist_home'))
    else:
        artist_dict = model_to_dict(artist)
        form = ArtistForm(artist_dict)
    return render(request, 'artist/artist_edit.html', {'form': form})

forms.py

class ArtistForm(forms.ModelForm):
    class Meta:
        model = Artist
        exclude =['user', ]

任何人都能够建议一种更好的方法来更新此 / 以消除错误?

【问题讨论】:

  • 而不是设置artist_status,你不能直接使用current_artist.has_created_artist_profile吗?你的问题是你把artist_status设置为current_artist.has_created_artist_profile,然后再试一次。
  • 感谢@RobertSeaman 好地方!我很愚蠢。已经从artist_status 中删除了has_created_artist_profile,所以现在基本上有artist_status = True artist_status.save() form.save(),但仍然收到相同的错误消息
  • 我认为你应该完全删除artist_status - 它增加了混乱。我想你想做current_artist.save()。你是如何创建artist_status 的?您是否尝试在不影响 current_artist 对象的情况下做某事?
  • 老兄,完全有效!非常感谢。刚刚迭代 current_artist,一切都很好。

标签: python django django-forms django-views


【解决方案1】:

'bool' object has no attribute 'has_created_artist_profile' 表示您正在尝试访问布尔对象(TrueFalse)的属性 has_created_artist_profile,而不是对象的属性。

例如: True.has_created_artist_profile 将产生完全相同的错误。

在您的代码中,您将 artist_status 设置为作为对象 (current_artist) 一部分的布尔值,然后尝试从该布尔值访问属性。

按照建议,您已删除 artist_status 变量,现在直接使用 current_artist 对象。

【讨论】:

  • 感谢罗伯特,这真的很有帮助!欣赏它。
猜你喜欢
  • 2021-07-06
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 2021-04-19
相关资源
最近更新 更多