I’ve seen this issue posted here multiple times and it is usually said to be an issue of the code but there is one from 10 days ago that seemed to not have an answer yet, so I’m thinking there still may be an issue in the code here?
Doing:
mgs = [] async for x in client.logs_from(client.get_channel('361683030932193281')): mgs.append(x) await client.delete_messages(mgs)
Getting «‘NoneType’ object has no attribute ‘id'»…
Tried doing it a multitude of different ways including having the get_channel code as it’s own line with a name and whatnot.
Traceback: https://i.imgur.com/z4ptQt3.png
Didn’t you just ask that in the server
And we answered you
I’m not in any server or asking questions elsewhere. If you have that many people asking the same question, perhaps it’s time to update the docs or make the code more clear. That’s actually kind of funny and really reinforces my point of a bunch of people asking the same question.
Oh then sorry (Wow what a world), is that a channel, are you calling that before the bot has started?
‘361683030932193281’ isn’t valid channel id and it returned None
The bot should be in the server. I’m converting it from being triggered by a message, to a background task being triggered on a timed basis. So I’m replacing (trying to, at least…) all the message.channel instances with an actual pre-defined channel ID.
I got that channel ID from both back-slashing the channel name, as well as hitting «Copy ID» by right-clicking the channel name.
get_channel
returns None when a channel with the specified channel ID was not found in the cache.
This raises some possibilities:
- The channel is not in cache yet. Try using
wait_until_ready
, which sleeps the coroutine until all channels, guilds and members are available in cache. - This channel doesn’t exist (you copied the ID wrong or similar)
- The bot logged in can’t actually see the channel (this doesn’t mean that it can’t read from it and should only happen when not in a mutual guild)
Judging by your last comment, I’m going to guess it’s the first one. Stick a
await client.wait_until_ready()
before your main code and see if it fixes the problem.
That fixed it. (wait_until_ready(), not the rest) Thanks, Gorialis. Great answer.
That fixed it. (wait_until_ready(), not the rest) Thanks, Gorialis. Great answer.
could u explain how to add this
Repository owner
locked as resolved and limited conversation to collaborators
Oct 28, 2020
We raise a Python AttributeError when we try to call or access an attribute of an object that does not exist for that object.
This tutorial will go through what an attribute is, what the AttributeError is in detail, and we will go through four examples to learn how to solve the error.
Table of contents
- What is a Python AttributeError?
- Example #1: Trying to Use append() on a String
- Solution
- Example #2: Trying to Access an Attribute of a Class that does not exist
- Solution
- Example #3: NoneType Object has no Attribute
- Solution
- Example #4: Handling Modules
- Solution
- Summary
What is a Python AttributeError?
An attribute of an object is a value or a function associated with that object. We can express calling a method of a class as referencing an attribute of a class.
Let’s look at an example of a Python class for the particle electron
class Electron:
def __init__(self):
self.charge = -1
self.mass = 0.51
self.spin = 1/2
def positron(self):
self.charge = +1
return self.charge
We can think of an attribute in Python as a physical attribute of an object. In this example, the fundamental particle, the electron, has physical attributes of charge, mass, and spin. The Electron class has the attributes charge, mass, and spin.
An attribute can also be a function. The function positron() returns the charge of the electron’s anti-particle, the positron.
Data types can have attributes. For example, the built-in data type List has the append() method to append elements to an existing list. Therefore, List objects support the append() method. Let’s look at an example of appending to a list:
a_list = [2, 4, 6]
a_list.append(8)
print(a_list)
Attributes have to exist for a class object or a data type for you to reference it. If the attribute is not associated with a class object or data type, you will raise an AttributeError.
Example #1: Trying to Use append() on a String
Let’s look at an example scenario where we concatenate two strings by appending one string to another.
string1 = "research"
string2 = "scientist"
string1.append(string2)
Using append() is impossible because the string data type does not have the append() method. Let’s run the code to see what happens:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
1 string1.append(string2)
AttributeError: 'str' object has no attribute 'append'
Solution
To solve this problem, we need to define a third string. We can then concatenate the two strings using the + symbol and assign the result to the third string. We can concatenate a space between the two strings so that the words do not run together. Let’s look at how the revised code:
string1 = "research"
string2 = "scientist"
string3 = string1 + " " + string2
print(string3)
research scientist
Example #2: Trying to Access an Attribute of a Class that does not exist
Let’s look at an example scenario where we want to access an attribute of a class that does not exist. We can try to create an instance of the class Electron from earlier in the tutorial. Once we have the instance, we can try to use the function get_mass() to print the mass of the electron in MeV.
class Electron:
def __init__(self):
self.charge = -1
self.mass = 0.51
self.spin = 1/2
def positron(self):
self.charge = +1
return self.charge
electron = Electron()
mass = electron.get_mass()
If we try to run the code, we get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
1 mass = electron.get_mass()
AttributeError: 'Electron' object has no attribute 'get_mass'
The Electron class has no attribute called get_mass(). Therefore we raise an AttributeError.
Solution
To solve this, we can do two things. We can add the method to the class and use a try-except statement. First, let’s look at adding the method:
class Electron:
def __init__(self):
self.charge = -1
self.mass = 0.51
self.spin = 1/2
def positron(self):
self.charge = +1
return self.charge
def get_mass(self):
return self.mass
electron = Electron()
mass = electron.get_mass()
print(f' The mass of the electron is {mass} MeV')
The mass of the electron is 0.51 MeV
Secondly, let’s look at using try-except to catch the AttributeError. We can use try-except statements to catch any error, not just AttributeError. Suppose we want to use a method called get_charge() to get the charge of the electron object, but we are not sure whether the Electron class contains the get_charge() attribute. We can enclose the call to get_charge() in a try-except statement.
class Electron:
def __init__(self):
self.charge = -1
self.mass = 0.51
self.spin = 1/2
def positron(self):
self.charge = +1
return self.charge
def get_mass(self):
return self.mass
electron = Electron()
try:
charge = electron.get_charge()
except Exception as e:
print(e)
'Electron' object has no attribute 'get_charge'
Using try-except statements aligns with professional development and makes your programs less prone to crashing.
Example #3: NoneType Object has no Attribute
NoneType means that whatever class or object you are trying to access is None. Therefore, whenever you try to do a function call or an assignment for that object, it will raise the AttributeError: ‘NoneType’ object has no attribute. Let’s look at an example scenario for a specific NoneType attribute error. We will write a program that uses regular expressions to search for an upper case “S” character at the beginning and print the word. We need to import the module re for regular expression matching.
import re
# Search for an upper case "S" character in the beginning of a word then print the word
string = "Research Scientist"
for i in string.split():
x = re.match(r"bSw+", i)
print(x.group())
Let’s run the code and see what happens:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
1 for i in string.split():
2 x = re.match(r"bSw+", i)
3 print(x.group())
4
AttributeError: 'NoneType' object has no attribute 'group'
We raise the AttributeError because there is no match in the first iteration. Therefore x returns None. The attribute group() does not belong to NoneType objects.
Solution
To solve this error, we want to only call group() for the situation where there is a match to the regular expression. We can therefore use the try-except block to handle the AttributeError. We can use continue to skip when x returns None in the for loop. Let’s look at the revised code.
import re
# Search for an upper case "S" character in the beginning of a word then print the word
string = "Research Scientist"
for i in string.split():
x = re.match(r"bSw+", i)
try:
print(x.group())
except AttributeError:
continue
Scientist
We can see that the code prints out Scientist, which is the word that has an upper case “S” character.
Example #4: Handling Modules
We can encounter an AttributeError while working with modules because we may call a function that does not exist for a module. Let’s look at an example of importing the math module and calling a function to perform a square root.
import math
number = 9
square_root_number = math.square_root(number)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
1 square_root_number = math.square_root(number)
AttributeError: module 'math' has no attribute 'square_root'
The module math does not contain the attribute square_root. Therefore we get an AttributeError.
Solution
To solve this error, you can use the help() function to get the module’s documentation, including the functions that belong to the module. We can use the help function on the math module to see which function corresponds to the square root.
import math
help(math)
sqrt(x, /)
Return the square root of x.
The function’s name to return the square root of a number is sqrt(). We can use this function in place of the incorrect function name.
square_root_number = math.sqrt(number)
print(square_root_number)
3.0
The code successfully returns the square root of 9. You can also use help() on classes defined in your program. Let’s look at the example of using help() on the Electron class.
help(Electron)
class Electron(builtins.object)
| Methods defined here:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| get_mass(self)
|
| positron(self)
The help() function returns the methods defined for the Electron class.
Summary
Congratulations on reading to the end of this tutorial. Attribute errors occur in Python when you try to reference an invalid attribute.
- If the attribute you want for built-in data types does not exist, you should look for an attribute that does something similar. For example, there is no append() method for strings but you can use concatenation to combine strings.
- For classes that are defined in your code, you can use help() to find out if an attribute exists before trying to reference it. If it does not exist you can add it to your class and then create a new instance of the class.
- If you are not sure if a function or value does not exist or if a code block may return a NoneType object, you can wrap the code in a try-except statement. Using a try-except stops your program from crashing if you raise an AttributeError.
For further reading on AttributeError, you can go to the following article: How to Solve Python AttributeError: ‘list’ object has no attribute ‘split’
Go to the online courses page on Python to learn more about Python for data science and machine learning.
Have fun and happy researching!
Я настроил функцию validate
внутри rest_framework_simplejwt
так, чтобы при аутентификации пользователя она вызывала сигнал user_logged_in
, чтобы я мог видеть, вошел пользователь в систему или нет.
Проблема, с которой я столкнулся, заключается в том, что когда пользователь входит в систему, но вводит неправильные данные для входа, я получаю сообщение об ошибке:
AttributeError at /api/token/
'NoneType' object has no attribute 'id'
Вот полное отслеживание:
Traceback (most recent call last):
File "C:Users15512anaconda3libsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "C:Users15512anaconda3libsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:Users15512anaconda3libsite-packagesdjangoviewsdecoratorscsrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:Users15512anaconda3libsite-packagesdjangoviewsgenericbase.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:Users15512anaconda3libsite-packagesrest_frameworkviews.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:Users15512anaconda3libsite-packagesrest_frameworkviews.py", line 469, in handle_exception
tokens.py", line 176, in for_user
user_id = getattr(user, api_settings.USER_ID_FIELD)
AttributeError: 'NoneType' object has no attribute 'id'
Вот моя функция валидации :
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
authenticate_kwargs = {
self.username_field: attrs[self.username_field],
"password": attrs["password"],
}
try:
authenticate_kwargs["request"] = self.context["request"]
except KeyError:
pass
user = authenticate(**authenticate_kwargs)
tokens = RefreshToken.for_user(user)
user_logged_in.send(sender=user.__class__, request=self.context['request'], user=user)
if not api_settings.USER_AUTHENTICATION_RULE(user):
raise exceptions.AuthenticationFailed(
self.error_messages["no_active_account"],
"no_active_account",
)
return {
'refresh': str(tokens),
'access': str(tokens.access_token),
'user': str(user),
}
Это функция, которая обрабатывает вход/аутентификацию пользователя
Вернуться на верх
0 / 0 / 0
Регистрация: 28.11.2019
Сообщений: 20
1
Discord Bot
31.12.2020, 18:40. Показов 3377. Ответов 1
Python | ||
|
Команда для создания 20 голосовых каналов в определенной категории с доступом к ним определенных ролей.
Overwrites находятся в цикле потому что role2 меняется. Change_1_letter — функция для замены букв, в ней ошибок нет, она работает правильно. Вот ошибка, появляющаяся при вводе команды.
Код
Ignoring exception in command createvoicechannels: Traceback (most recent call last): File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandscore.py", line 83, in wrapped ret = await coro(*args, **kwargs) File "C:UsersplaysOneDriveРабочий столPythonbot2.py", line 59, in createvoicechannels await ctx.channel.guild.create_voice_channel(name = f"l-Пати-#{i}-l", category = ctx.channel.category, overwrites = overwrites) File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordguild.py", line 888, in create_voice_channel data = await self._create_channel(name, overwrites, ChannelType.voice, category, reason=reason, **options) File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordguild.py", line 771, in _create_channel 'id': target.id AttributeError: 'NoneType' object has no attribute 'id' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandsbot.py", line 892, in invoke await ctx.command.invoke(ctx) File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandscore.py", line 797, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandscore.py", line 92, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
В чем заключается ошибка и как ее исправить?
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
Мне удалось перейти к седьмой главе книги «Разработка через тестирование на Python».
Я просмотрел все темы об одних и тех же ошибках в Google, но объяснения отличаются от моего теста. Поэтому я изо всех сил пытаюсь понять, что не так с кодом ниже. Я понимаю что
AttributeError: 'NoneType' object has no attribute 'id'
говорит мне, 'id'
не определен. Но я не знаю, где это исправить в Джанго.
Также для
self.assertEqual(Item.objects.count(), 1)
AssertionError: 0 != 1,
Я не знаю, где искать.
(sup) [email protected]:~/sup1/superlists$ sudo python3 manage.py test lists
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
======================================================================
ERROR: test_redirects_after_POST (lists.tests.NewListTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/tim/sup1/superlists/lists/tests.py", line 93, in test_redirects_after_POST
self.assertRedirects(response, f'/lists/{new_list.id}/')
AttributeError: 'NoneType' object has no attribute 'id'
======================================================================
FAIL: test_can_save_a_POST_request (lists.tests.NewListTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/tim/sup1/superlists/lists/tests.py", line 87, in test_can_save_a_POST_request
self.assertEqual(Item.objects.count(), 1)
AssertionError: 0 != 1
MODELS.PY
from django.db import models
class List(models.Model):
pass
class Item(models.Model):
text = models.TextField(default='')
list = models.ForeignKey(List, default='', null=True, blank=True, on_delete = models.CASCADE)
TESTS.PY
from django.template.loader import render_to_string
from django.urls import resolve, reverse_lazy
from django.test import TestCase
from django.http import HttpRequest
from lists.views import home_page
from lists.models import Item, List
class HomePageTest(TestCase):
def test_uses_home_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'home.html')
def test_displays_all_list_items(self):
Item.objects.create(text='itemey 1')
# Item.objects.create(text='itemey 2')
response = self.client.get('/')
self.assertIn('item', response.content.decode())
# self.assertIn('itemey 2', response.content.decode())
def test_only_saves_items_when_necessary(self):
self.client.get('/')
self.assertEqual(Item.objects.count(), 0)
class ListViewTest(TestCase):
def test_uses_list_template(self):
list_ = List.objects.create()
response = self.client.get(f'/lists/{list_.id}/')
self.assertTemplateUsed(response, 'list.html')
def test_displays_only_items_for_that_list(self):
correct_list = List.objects.create()
Item.objects.create(text='item', list=correct_list)
# Item.objects.create(text='itemey 2', list=correct_list)
response = self.client.get(f'/lists/{correct_list.id}/')
self.assertContains(response, 'item')
# self.assertContains(response, 'itemey 2')
def test_passes_correct_list_to_template(self):
correct_list = List.objects.create()
response = self.client.get(f'/lists/{correct_list.id}/')
self.assertEqual(response.context['list'], correct_list)
class ListAndItemModelsTest(TestCase):
def test_saving_and_retrieving_items(self):
list_ = List()
list_.save()
first_item = Item()
first_item.text = 'The first (ever) list item'
first_item.list = list_
first_item.save()
second_item = Item()
second_item.text = 'Item the second'
second_item.list = list_
second_item.save()
saved_list = List.objects.first()
self.assertEqual(saved_list, list_)
saved_items = Item.objects.all()
self.assertEqual(saved_items.count(), 2)
first_saved_item = saved_items[0]
second_saved_item = saved_items[1]
self.assertEqual(first_saved_item.text, 'The first (ever) list item')
self.assertEqual(first_saved_item.list, list_)
self.assertEqual(second_saved_item.text, 'Item the second')
self.assertEqual(second_saved_item.list, list_)
class NewListTest(TestCase):
def test_can_save_a_POST_request(self):
self.client.post('lists/new', {'item_text': 'A new list item'})
new_item = Item.objects.first()
self.assertEqual(Item.objects.count(), 1)
self.assertEqual(new_item.text, 'A new list item')
def test_redirects_after_POST(self):
response = self.client.post('/lists/new', data={'item_text': 'A new list item'})
new_list = List.objects.first()
self.assertRedirects(response, f'/lists/{new_list.id}/')
class NewItemTest(TestCase):
def test_can_save_a_POST_request_to_an_existing_list(self):
correct_list = List.objects.create()
self.client.post(
f'/lists/{correct_list.id}/add_item',
data={'item_text': 'A new item for an existing list'}
)
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new item for an existing list')
self.assertEqual(new_item.list, correct_list)
def test_redirects_to_list_view(self):
correct_list = List.objects.create()
response = self.client.post(
f'/lists/{correct_list.id}/add_item',
data={'item_text': 'A new item for an existing list'}
)
self.assertRedirects(response, f'/lists/{correct_list.id}/')
VIEWS.PY
from django.shortcuts import redirect, render
# from django.http import HttpResponse
from lists.models import Item, List
def home_page(request):
if request.method == 'POST':
Item.objects.create(text=request.POST['item_text'])
return redirect('/')
items = Item.objects.all()
return render(request, 'home.html')
def view_list(request, list_id):
list_ = List.objects.get()
return render(request, 'list.html', {'list': list_})
def new_list(request):
list_ = List.objects.create()
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect(f'/lists/{list.id}/')
def add_item(request, list_id):
list_ = List.objects.get(id=list_id)
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect(f'/lists/{list_.id}/')
SUPERLIST — URLS.PY
from django.urls import path, re_path, include
from lists import views as list_views
from lists import urls as list_urls
urlpatterns = [
#path('admin/', admin.site.urls),
re_path('^$', list_views.home_page, name="home"),
path('lists/', include(list_urls)),
re_path('^lists/new/$', list_views.new_list, name="new_list"),
re_path('^lists/(d+)/$', list_views.view_list, name="view_list"),
re_path('^lists/(d+)/add_item$', list_views.add_item, name="add_item"),
]
СПИСОК — URLS.PY
#from django.contrib import admin
from django.urls import path, re_path
from lists import views
urlpatterns = [
#path('admin/', admin.site.urls),
re_path('^new/$', views.new_list, name="new_list"),
re_path('^(d+)/$', views.view_list, name="view_list"),
re_path('^(d+)/add_item$', views.add_item, name="add_item"),
]
home.html
<html>
<head>
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST" action="/lists/new">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item" />
{% csrf_token %}
</form>
</body>
</html>
list.html
{% extends 'home.html' %}
<body>
<h1>Start a new To-Do list</h1>
<form method="POST" action="/lists/{{ list.id }}/add_item">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item" />
{% csrf_token %}
</form>
<table id="id_list_table">
{% for item in list.item_set.all %}
<tr><td>{{ forloop.counter }}: {{ item.text }}</td></tr>
{% endfor %}
</table>
</body>
Я пытаюсь сохранить пользовательский ввод и убедиться, что страницы перенаправляются правильно, но пока не достигли большого успеха.
Hello,
I added a custom layout to my report but this is what I am getting:
Error:
Odoo Server Error
Traceback (most recent call last):
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/qweb.py», line 332, in _compiled_fn
return compiled(self, append, new, options, log)
File «», line 1, in template_river_report_alhaddar_layout_standard_1500
AttributeError: ‘NoneType’ object has no attribute ‘id’
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File «/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py», line 2025, in report_download
response = self.report_routes(reportname, docids=docids, converter=converter, context=context)
File «/usr/lib/python3/dist-packages/odoo/http.py», line 515, in response_wrap
response = f(*args, **kw)
File «/home/ubuntu/custom_modules/report_xlsx_helper/controllers/main.py», line 56, in report_routes
reportname, docids, converter, **data
File «/usr/lib/python3/dist-packages/odoo/http.py», line 515, in response_wrap
response = f(*args, **kw)
File «/home/ubuntu/custom_modules/report_xlsx/controllers/main.py», line 49, in report_routes
reportname, docids, converter, **data
File «/usr/lib/python3/dist-packages/odoo/http.py», line 515, in response_wrap
response = f(*args, **kw)
File «/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py», line 1963, in report_routes
pdf = report.with_context(context).render_qweb_pdf(docids, data=data)[0]
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions_report.py», line 734, in render_qweb_pdf
html = self.with_context(context).render_qweb_html(res_ids, data=data)[0]
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions_report.py», line 774, in render_qweb_html
return self.render_template(self.report_name, data), ‘html’
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions_report.py», line 548, in render_template
return view_obj.render_template(template, values)
File «/home/ubuntu/custom_modules/app_odoo_customize/models/ir_ui_view.py», line 18, in render_template
return super(View, self).render_template(template, values=values, engine=engine)
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_ui_view.py», line 1177, in render_template
return self.browse(self.get_view_id(template)).render(values, engine)
File «/usr/lib/python3/dist-packages/odoo/addons/web_editor/models/ir_ui_view.py», line 27, in render
return super(IrUiView, self).render(values=values, engine=engine, minimal_qcontext=minimal_qcontext)
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_ui_view.py», line 1185, in render
return self.env[engine].render(self.id, qcontext)
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_qweb.py», line 58, in render
result = super(IrQWeb, self).render(id_or_xml_id, values=values, **context)
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/qweb.py», line 260, in render
self.compile(template, options)(self, body.append, values or {})
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/qweb.py», line 334, in _compiled_fn
raise e
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/qweb.py», line 332, in _compiled_fn
return compiled(self, append, new, options, log)
File «», line 1, in template_river_report_report_hr_statement_1474
File «», line 2, in body_call_content_1472
File «», line 3, in foreach_1471
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/qweb.py», line 339, in _compiled_fn
raise QWebException(«Error to render compiling AST», e, path, node and etree.tostring(node[0], encoding=’unicode’), name)
odoo.addons.base.models.qweb.QWebException: ‘NoneType’ object has no attribute ‘id’
Traceback (most recent call last):
File «/usr/lib/python3/dist-packages/odoo/addons/base/models/qweb.py», line 332, in _compiled_fn
return compiled(self, append, new, options, log)
File «», line 1, in template_river_report_alhaddar_layout_standard_1500
AttributeError: ‘NoneType’ object has no attribute ‘id’
Error to render compiling AST
AttributeError: ‘NoneType’ object has no attribute ‘id’
Template: river_report.alhaddar_layout_standard
Path: /t/div[1]
Node:
- :
- Tel:
Introduction
Problem: How to solve “AttributeError: ‘NoneType’ object has no attribute ‘something’ “?
An AttributeError
is raised in Python when you attempt to call the attribute of an object whose type does not support the method. For example, attempting to utilize the append()
method on a string returns an AttributeError
as lists use the append()
function and strings don’t support it.
Example:
# A set of strings names = {"John", "Rashi"} names.extend("Chris") print(names)
Output:
Traceback (most recent call last):
File "C:UsersSHUBHAM SAYONPycharmProjectsFinxerErrorsAttributeError - None Type Object.py", line 3, in <module>
names.extend("Chris")
AttributeError: 'set' object has no attribute 'extend'
Hence, if you attempt to reference a value or function not related to a class object or data type, it will raise an AttributeError.
AttributeError:’NoneType’ object has no attribute ‘something’
Different reasons raise AttributeError: 'NoneType' object has no attribute 'something'
. One of the reasons is that NoneType
implies that instead of an instance of whatever Class or Object that you are working with, in reality, you have got None
. It implies that the function or the assignment call has failed or returned an unforeseen outcome.
Let’s have a look at an example that leads to the occurrence of this error.
Example 1:
# Assigning value to the variable a = None print(a.something)
Output:
Traceback (most recent call last):
File "C:UsersSHUBHAM SAYONPycharmProjectsFinxerErrorsAttributeError - None Type Object.py", line 3, in <module>
print(a.something)
AttributeError: 'NoneType' object has no attribute 'something'
Hence, AttributeError: ‘NoneType’ object has no attribute ‘something’ error occurs when the type of object you are referencing is None. It can also occur when you reference a wrong function instead of the function used in the program.
Example:
# A function to print numbers def fun(x): if x <= 10: x = x + 1 return x a = fun(5) # Calling the function that does not exist print(a.foo())
Output:
Traceback (most recent call last):
File "C:UsersSHUBHAM SAYONPycharmProjectsFinxerErrorsAttributeError - None Type Object.py", line 10, in <module>
print(a.foo())
AttributeError: 'int' object has no attribute 'foo'
How to check if the operator is Nonetype?
Since this AttributeError revolves around the NoneType
object, hence it is of primary importance to identify if the object referred has a type None
. Thus, you can check if the operator is Nonetype
with the help of the “is
” operator. It will return True
if the object is of the NoneType
and return False
if not.
Example:
x = None if x is None: print("The value is assigned to None") else: print(x)
Output:
The value is assigned to None
Now that you know how AttributeError: ‘NoneType’ object has no attribute ‘something’ gets raised let’s look at the different methods to solve it.
#Fix 1: Using if and else statements
You can eliminate the AttributeError: 'NoneType' object has no attribute 'something'
by using the- if and else statements. The idea here is to check if the object has been assigned a None
value. If it is None
then just print a statement stating that the value is Nonetype
which might hamper the execution of the program.
Example:
x1 = None if x1 is not None: x1.some_attribute = "Finxter" else: print("The type of x1 is ", type(x1))
Output:
The type of x1 is <class 'NoneType'>
#Fix 2: Using try and except Blocks
You can also use the exception handling (try and except block) to solve the AttributeError: 'NoneType' object has no attribute 'something'
.
Example:
# A function to print numbers def fun(x): if x <= 10: x = x + 1 return x a = fun(5) # Using exception handling (try and except block) try: print(a) # Calling the function that does not exist print(a.foo()) except AttributeError as e: print("The value assigned to the object is Nonetype")
Output:
6
The value assigned to the object is Nonetype
Quick Review
Now that we have gone through the ways to fix this AttributeError
, let’s go ahead and visualize a few other situations which lead to the occurrence of similar attribute errors and then solve them using the methods we learned above.
1. ‘NoneType’ Object Has No Attribute ‘Group’
import re # Search for an upper case "S" character in the beginning of a word, and print the word: txt = "The rain in Spain" for i in txt.split(): x = re.match(r"bSw+", i) print(x.group())
Output:
Traceback (most recent call last):
File "D:/PycharmProjects/Errors/attribute_error.py", line 9, in <module>
print(x.group())
AttributeError: 'NoneType' object has no attribute 'group'
The code encounters an attribute error because in the first iteration it cannot find a match, therefore x
returns None. Hence, when we try to use the attribute for the NoneType object, it returns an attribute error.
Solution: Neglect group()
for the situation where x
returns None
and thus does not match the Regex. Therefore use the try-except
blocks such that the attribute error is handled by the except block.
import re txt = "The rain in Spain" for i in txt.split(): x = re.match(r"bSw+", i) try: print(x.group()) except AttributeError: continue # Output : Spain
2. Appending list But error ‘NoneType’ object has no attribute ‘append’
li = [1, 2, 3, 4] for i in range(5): li = li.append(i) print(li)
Output:
Traceback (most recent call last):
File "C:UsersSHUBHAM SAYONPycharmProjectsFinxerErrorsAttributeError - None Type Object.py", line 3, in <module>
li = li.append(i)
AttributeError: 'NoneType' object has no attribute 'append'
Solution:
When you are appending to the list as i = li.append(i)
you are trying to do an inplace operation which modifies the object and returns nothing (i.e. None
). In simple words, you should not assign the value to the li
variable while appending, it updates automatically. This is how it should be done:
li = [1, 2, 3, 4] for i in range(5): li.append(i) print(li) # output: [1, 2, 3, 4, 0, 1, 2, 3, 4]
Conclusion
To sum things up, there can be numerous cases wherein you wil encounter an attribute error of the above type. But the underlying reason behind every scenario is the same, i.e., the type of object being referenced is None. To handle this error, you can try to rectify the root of the problem by ensuring that the object being referenced is not None. You may also choose to bypass the error based on the requirement of your code with the help of try-cath blocks.
I hope this article helped you to gain a deep understanding of attribute errors. Please stay tuned and subscribe for more interesting articles and discussions.
To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members:
I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.
You can contact me @:
UpWork
LinkedIn