【问题标题】:Django 'NoneType' object is not callableDjango 'NoneType' 对象不可调用
【发布时间】:2021-06-04 04:46:32
【问题描述】:

我尝试使用 BeautifulSoup 从 class、id 等中清除 html,然后保存它们。

清除 html 工作正常,但是当我尝试保存时,我得到:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 754, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 792, in save_base
    force_update, using, update_fields,
  File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 873, in _save_table
    forced_update)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_update
    return filtered._update(values) > 0
  File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 799, in _update
    query.add_update_fields(values)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/subqueries.py", line 108, in add_update_fields
    val = val.resolve_expression(self, allow_joins=False, for_save=True)
TypeError: 'NoneType' object is not callable

我的代码:

@shared_task
def clean_article_html(article_id):
    try:
        article = Article.objects.get(id=article_id)
    except ObjectDoesNotExist:
        pass
    else:
        html = BeautifulSoup(article.body, 'html.parser')
        for tag in html():
            for attribute in ['class', 'id', 'name', 'style']:
                del tag[attribute]
        
        article.text = html
        article.save()

也许有人知道这段代码有什么问题。

解决方案:(感谢 AbdulAzizBarkat)

article.text = str(html)
article.save()

【问题讨论】:

  • 模型可能有问题。你介意用你的模型类更新你的问题吗?
  • article 对象可能是None,您的代码可能在exception 块中,但您已经pass 编辑了它,因此您可以尝试检查exception
  • for tag in html()article.text = html。是否缺少() 来调用函数?
  • 试试article.text = str(html),如果还是不行,请将full错误回溯添加到问题中。
  • @AbdulAzizBarkat 您的解决方案工作!谢谢!

标签: django django-models beautifulsoup


【解决方案1】:

试试这个

@shared_task
def clean_article_html(article_id):
    try:
        article = Article.objects.get(id=article_id)
        html = BeautifulSoup(article.body, 'html.parser')
        for tag in html():
            for attribute in ['class', 'id', 'name', 'style']:
                del tag[attribute]
        
        article.text = html
        article.save()
    except ObjectDoesNotExist:
        pass
  
        

【讨论】:

  • 这样更好吗?您所做的只是让 try 块封装所有逻辑(糟糕的设计!保持 try-except 块尽可能小)。事实上 OP 的原始代码更好(else 确保代码只有在没有异常发生时才运行)
猜你喜欢
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 2019-08-12
  • 2012-08-10
  • 2015-04-29
相关资源
最近更新 更多