FieldError on ManyToMany after upgrading to Django 1.3 - python

Just been updating to Django 1.3 and come across an odd error. I'm getting the following error from some code which works with version 1.2.7.
FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type
The odd thing being email_config_set is a related name for a ManyToMany field. I'm not sure why django is trying to resolve it into a field.
The error occurs deep inside django:
Traceback (most recent call last):
File "./core/driver.py", line 268, in run
self.init_norm()
File "./driver/emailevent/background.py", line 130, in init_norm
self.load_config()
File "./driver/emailevent/background.py", line 71, in load_config
events = list(config.events.select_related())
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/manager.py", line 168, in select_related
return self.get_query_set().select_related(*args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/fields/related.py", line 497, in get_query_set
return superclass.get_query_set(self).using(db)._next_is_sticky().filter(**(self.core_filters))
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1194, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1069, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1260, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type
Any pointers or tips would be welcome.

The problem in this case was due to dynamic models, and their creation order. More specifically, some models which were dynamically created after others, were not defined when the _meta caches were filled, and therefore lead to errors. Clearing the caches or changing the creation order resolves this problem.
See also https://groups.google.com/d/msg/django-users/RJlV5_ribZk/P6tv4QlJN4EJ

Related

Odoo 14, issue when trying to computing bank balance in treasury module

i got work to fix error when computing but i still dont have idea how to fix it because i'm still newbie
Odoo Server Error
Traceback (most recent call last): File
"/home/equipAccounting/equip/odoo/addons/base/models/ir_http.py", line
237, in _dispatch
result = request.dispatch() File "/home/equipAccounting/equip/odoo/http.py", line 683, in dispatch
result = self._call_function(**self.params) File "/home/equipAccounting/equip/odoo/http.py", line 359, in
_call_function
return checked_call(self.db, args, *kwargs) File "/home/equipAccounting/equip/odoo/service/model.py", line 94, in
wrapper
return f(dbname, args, *kwargs) File "/home/equipAccounting/equip/odoo/http.py", line 347, in checked_call
result = self.endpoint(*a, **kw) File "/home/equipAccounting/equip/odoo/http.py", line 912, in call
return self.method(*args, **kw) File "/home/equipAccounting/equip/odoo/http.py", line 531, in response_wrap
response = f(*args, **kw) File "/home/equipAccounting/equip/addons/basic/web/controllers/main.py",
line 1393, in call_button
action = self._call_kw(model, method, args, kwargs) File "/home/equipAccounting/equip/addons/basic/web/controllers/main.py",
line 1381, in _call_kw
return call_kw(request.env[model], method, args, kwargs) File "/home/equipAccounting/equip/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs) File "/home/equipAccounting/equip/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, args, *kwargs) File "/home/equipAccounting/equip/addons/core/treasury_forecast/models/treasury_bank_forecast.py",
line 290, in compute_bank_balances
self.env.cr.execute(main_query) File "/usr/local/lib/python3.8/dist-packages/decorator.py", line 232, in
fun
return caller(func, (extras + args), *kw) File "/home/equipAccounting/equip/odoo/sql_db.py", line 101, in check
return f(self, args, *kwargs) File "/home/equipAccounting/equip/odoo/sql_db.py", line 298, in execute
res = self._obj.execute(query, params) Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File
"/home/equipAccounting/equip/odoo/http.py", line 639, in
_handle_exception
return super(JsonRequest, self)._handle_exception(exception) File "/home/equipAccounting/equip/odoo/http.py", line 315, in
_handle_exception
raise exception.with_traceback(None) from new_cause psycopg2.errors.SyntaxError: syntax error at or near ")" LINE 9:
WHERE abs.journal_id IN ()
and here is the code :
def get_bank_fc_query(self, fc_journal_list, date_start, date_end,company_domain):
query = """
UNION
SELECT CAST('FBK' AS text) AS type, absl.id AS ID, am.date, absl.payment_ref as name, am.company_id, absl.amount_main_currency as amount, absl.cf_forecast, abs.journal_id, NULL as kind FROM account_bank_statement_line absl
LEFT JOIN account_move am ON (absl.move_id = am.id)
LEFT JOIN account_bank_statement abs ON (absl.statement_id = abs.id)
WHERE abs.journal_id IN {}
AND am.date BETWEEN '{}' AND '{}'
AND am.company_id in {} """
.format(str(fc_journal_list), date_start, date_end,company_domain)
return query
def get_acc_move_query(self, date_start, date_end, company_domain):
query = """
UNION
SELECT CAST('FPL' AS text) AS type, aml.id AS ID,aml.treasury_date AS date, am.name AS name, aml.company_id, aml.amount_residual AS amount, NULL AS cf_forecast,
NULL AS journal_id, am.move_type as kind
FROM account_move_line aml
LEFT JOIN account_move am ON (aml.move_id = am.id)
WHERE am.state NOT IN ('draft')
AND aml.treasury_planning AND aml.amount_residual != 0
AND aml.treasury_date BETWEEN '{}' AND '{}'
AND aml.company_id in {} """
.format(date_start, date_end, company_domain)
return query
Thanks in advance
The error has nothing to do with Odoo.
psycopg2.errors.SyntaxError: syntax error at or near ")" LINE 9:
WHERE abs.journal_id IN ()
It's cleary a syntax error in the query itself. You're using the IN operator without having a value list afterwards.
Your fc_journal_list parameter doesn't have values on your call. You should catch an empty list before creating the query.
And then there are atleast 2 big security risks in your code:
never ever use string formatting for querys, the comment under your question already points to variables in SQL queries that's the common mistake to make SQL injections an easy thing...
don't make such security risky methods (here both query returning methods) public to the odoo external API. Just add a _ at the beginning of the method names and you're fine on that part.
Odoo has a very powerful ORM API to do the psql queries. Is there a good reason you use sql instead?
The functions you need are, Read for selecting the fields you use, search and filtered for filtering the results.
I suggest reading the following tutorial.
https://www.odoo.com/documentation/14.0/developer/reference/addons/orm.html#search-read
also look at good examples inside the odoo source, I think the stock module is a good place to see some examples.
https://github.com/odoo/odoo/blob/14.0/addons/stock/models/stock_move.py
To fix the error without removing the query, In the function calling get_bank_fc_query you have to check for empty lists first. In python that is very easy, becouse everything that is empty equals False, so do this:
if not fc_journal_list:
raise exceptions.UserError('fc_journal_list cannot be empty')
query = self.get_bank_fc_query(fc_journal_list, date_start, date_end,company_domain
....

TypeError: '_SentinelObject' object is not callable

I am upgrading my Django application from version 2.2 to 3.2. while upgrading i am facing below issue, i have spent a lot of time to resolve this but didn't get any solution yet.
here's the traceback of issue which i am facing:
File ".../abc/test.py", line 85, in setUp
self.MODEL_A.save()
File ".../abc/models.py", line 470, in save
super(MODEL_A, self).save(*args, **kwargs)
File ".../lib/python3.8/site-packages/django/db/models/base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File ".../lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base
updated = self._save_table(
File ".../lib/python3.8/site-packages/django/db/models/base.py", line 842, in _save_table
values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
File ".../lib/python3.8/site-packages/django/db/models/base.py", line 842, in <listcomp>
values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
File ".../lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1396, in pre_save
value = timezone.now()
TypeError: '_SentinelObject' object is not callable
Any help would be highly appreciated.
Thanks in advance.
Assigning objects which don't support copy.deepcopy() during setUpTestData() is deprecated. Either assign the unit attribute during setUpClass() or setUp(), or add support for deepcopy().
So there might be a code in your test cases like below:
#classmethod
def setUpTestData(cls):
super(YourTestClassNameHere, cls).setUpTestData()
Change this code as follows:
#classmethod
def setUpClass(cls):
super(YourTestClassNameHere, cls).setUpClass()
This will resolve your _SentinelObject issues.

Django: ModelChoiceField and django.setup()

If I try to run a test via PyCharm, I get this exception
...bin/python /usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py ...src/foo/foo/tests/FooEditTest.py::FooEditTest::test_issue_add true
Testing started at 15:59 ...
Traceback (most recent call last):
File "/usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py", line 139, in <module>
module = loadSource(a[0])
File "/usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py", line 41, in loadSource
module = imp.load_source(moduleName, fileName)
File "...src/foo/foo/tests/FooEditTest.py", line 45, in <module>
from foo.views.issue.forward import forward
File "...src/foo/foo/views/issue/forward.py", line 29, in <module>
class ForwardForm(forms.Form):
File "...src/foo/foo/views/issue/forward.py", line 36, in ForwardForm
group=forms.ModelChoiceField(Group.objects.exclude(groupconfig__no_issue=True).extra(
File "...python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "...python2.7/site-packages/django/db/models/query.py", line 698, in exclude
return self._filter_or_exclude(True, *args, **kwargs)
File "...python2.7/site-packages/django/db/models/query.py", line 707, in _filter_or_exclude
clone.query.add_q(~Q(*args, **kwargs))
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1331, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1358, in _add_q
current_negated=current_negated, connector=connector)
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1182, in build_filter
lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1120, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1383, in names_to_path
field, model, direct, m2m = opts.get_field_by_name(name)
File "...python2.7/site-packages/django/db/models/options.py", line 416, in get_field_by_name
cache = self.init_name_map()
File "...python2.7/site-packages/django/db/models/options.py", line 445, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "...python2.7/site-packages/django/db/models/options.py", line 563, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "...python2.7/site-packages/django/db/models/options.py", line 577, in _fill_related_many_to_many_cache
for klass in self.apps.get_models():
File "...python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper
result = user_function(*args, **kwds)
File "...python2.7/site-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "...python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Process finished with exit code 1
I use group=forms.ModelChoiceField(Group.objects.exclude(...))
This line gets executed during importing. The call to django.setup() was not done before.
I have no clue how to solve this:
Should I call django.setup()? But where to insert this line?
Avoid using MyModel.objects.filter(...) during import time? This would need a big refactoring, since we have several ModelChoiceFields.
You're currently running the tests using the PyCharm's Python unit test runner pycharm-4.5.1/helpers/pycharm/utrunner.py.
This test runner is great for low-level unit tests (subclassed from unittest.TestCase) that don't touch Django features like the ORM, but
if the tests rely on Django-specific things like the database, then your TestCases probably need to be subclassed from django.test.testcases.TestCase and you'll need to go through PyCharm's Django test manager django_test_manage.py, which takes care of setting up the test database, initialising the model registry, and so on.
Run > Edit Configurations > Add New Configuration (+ button) > Django Tests
Set the target to foo.foo.tests.FooEditTest and make sure to put DJANGO_SETTINGS_MODULE=... in the environment variables if it doesn't find your settings.
I faced the same problem while running test cases and solved it by adding this to test file at the beginning with import statements
import os
import sys
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()
Please show your exact code (especially the extra() clause). Calling filter() or exclude() at import time is not bad because querysets are lazy but you could evaluate the queryset here that caused the exception.
Do not evaluate querysets during import time because import statements are executed only once: e.g., if a new group is created, it won't be available as a choice for you ModelChoiceField.
A bit hard to say without seeing your code, but I had a similar issue once. For me it was related to a module that was being imported by my models and that also contained an import of my models.
ModelA --- imports --> service -- imports --> ModelA
I solved this by moving the import in my service to the method that needed the import. So instead of putting it at the top of the service module, I limited the scope of the import to the method that needed this import, thus avoiding importing the models whilst initializing the service module. Fwew, I wish I could draw it for you :)

Django - A model can't have more than one AutoField

This problem randomly started appearing for me. I know that Django generates its own ids but a lot my code has been using custom AutoFields which HAS been working. I added a new class today and tried to makemigrations but this error keeps showing up.
I DID remove all instances of AutoFields and retried migrating but the problem still persists which leads me to believe it's something else... I don't believe my Django version has changed at all...
Error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
338, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 390,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 441,
in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\makemigrat
ions.py", line 98, in handle
loader.project_state(),
File "C:\Python34\lib\site-packages\django\db\migrations\loader.py", line 326,
in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self
.unmigrated_apps))
File "C:\Python34\lib\site-packages\django\db\migrations\graph.py", line 231,
in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 8
3, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py"
, line 51, in state_forwards
state.reload_model(app_label, self.model_name_lower)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 152,
in reload_model
self.apps.render_multiple(states_to_be_rendered)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 262,
in render_multiple
model.render(self)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 546,
in render
body,
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 189, in __
new__
new_class.add_to_class(obj_name, obj)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 324, in ad
d_to_class
value.contribute_to_class(cls, name)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line
989, in contribute_to_class
"A model can't have more than one AutoField."
AssertionError: A model can't have more than one AutoField.
Here's an example of one of my fields:
assetid = models.AutoField(primary_key=True)
A lot of my code already depends on the name itself so changing it is going to be a big issue. Furthermore, this was working perfectly before! I just can't seem to migrate it now. I should mention im using a sqlite3 db.
This is Because Django By default uses AutoField for the id.....so, if you want other fields to be AutoField, then make sure you confirm primary_key=True.
Doing so deletes the id field from the Database.
I have used Mysql as my database. Be sure this problem might not solve in other databases.
Deleted migration files and most recent history and fixed it.
I was having the same problem,
I commented out all the references to that model in all my app files, then run makemigrations and migrate, butit keeps telling that "A model can't have more than one AutoField." even if i am trying to deleting that file.
I had to reset my database.
in my case I deleted id Autofield ,it works fine for me as Django uses Autofield by default
better way is just unapply migrations(meaning run a previous migration).in this way the fields which sometimes are not removed from database are automatically removed from database.Then, after changes you can easily do makemigrations again and then migrate and everything will be good.

How to Integrate Pyramid 1.1 and Mongo DB - as few lines as possible

Goal: I try to integrate Mongo DB with Pyramid 1.1 basic application.
Background: Appliation is created by the book (https://docs.pylonsproject.org/projects/pyramid/1.1/narr/project.html#creating-the-project) using basic command "paste create -t pyramid_starter"
I followed this cookbook article: https://docs.pylonsproject.org/projects/pyramid_cookbook/dev/mongo.html
Problem: It seems that when ever I add MongoDB connection into request I got "Internal Server Error" with
I have tried several articles and it seems that I must start debug system more?
Has anybody found easy solution for this?
Exception if it helps some expert
Exception happened during processing of request from ('127.0.0.1', 53697)
Traceback (most recent call last):
File "virtualenv\lib\site-packages\paste-1.7.5.1-py2.7.egg\paste\httpserver.py", line 1068, in process_request_in_thread
self.finish_request(request, client_address)
File "C:\Python27\Lib\SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\Lib\SocketServer.py", line 639, in __init__
self.handle()
File "virtualenv\lib\site-packages\paste-1.7.5.1-py2.7.egg\paste\httpserver.py", line 442, in handle
BaseHTTPRequestHandler.handle(self)
File "C:\Python27\Lib\BaseHTTPServer.py", line 343, in handle
self.handle_one_request()
...
File "C:\Python27\lib\site-packages\pyramid_debugtoolbar-0.8-py2.7.egg\pyramid_debugtoolbar\panels\__init__.py", line 24, in render
return render(template_name, vars, request=request)
File "virtualenv\lib\site-packages\pyramid-1.2a1-py2.7.egg\pyramid\renderers.py", line 69, in render
return helper.render(value, None, request=request)
File "virtualenv\lib\site-packages\pyramid-1.2a1-py2.7.egg\pyramid\renderers.py", line 418, in render
result = renderer(value, system_values)
File "C:\Python27\lib\site-packages\pyramid_jinja2-1.1-py2.7.egg\pyramid_jinja2\__init__.py", line 277, in __call__
return self.template.render(system)
File "C:\Python27\lib\site-packages\jinja2-2.6-py2.7.egg\jinja2\environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Python27\lib\site-packages\pyramid_debugtoolbar-0.8-py2.7.egg\pyramid_debugtoolbar\panels\templates\request_vars.jinja2", line 110, in top-level template code
<td>{{ value|escape }}</td>
File "virtualenv\lib\site-packages\markupsafe-0.15-py2.7.egg\markupsafe\_native.py", line 20, in escape
return s.__html__()
File "virtualenv\lib\site-packages\pymongo-2.0.1-py2.7-win-amd64.egg\pymongo\collection.py", line 1156, in __call__
self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the '__html__' method on a 'Database' object it is failing because no such method exists.
Another possible solution is to use the 'debugtoolbar.panels' setting in your config file to disable the request_vars panel (which is what is causing the issue):
[app:main]
.. other stuff ...
debugtoolbar.panels =
pyramid_debugtoolbar.panels.versions.VersionDebugPanel
pyramid_debugtoolbar.panels.settings.SettingsDebugPanel
pyramid_debugtoolbar.panels.headers.HeaderDebugPanel
# pyramid_debugtoolbar.panels.request_vars.RequestVarsDebugPanel
pyramid_debugtoolbar.panels.renderings.RenderingsDebugPanel
pyramid_debugtoolbar.panels.logger.LoggingPanel
pyramid_debugtoolbar.panels.performance.PerformanceDebugPanel
pyramid_debugtoolbar.panels.routes.RoutesDebugPanel
pyramid_debugtoolbar.panels.sqla.SQLADebugPanel
Pymongo's Database and Collection objects respond to __getattr__ in order to provide a nicer interface and let you write code like:
db.foo.bar.find(...)
Any call to __getattr__ will succeed, but unfortunately this confuses some libraries which expect certain attributes to be callable (the Pymongo Collection object is not callable, except to raise that exception you're seeing above).
What I've done in Pyramid projects is only use the database from within the resources, to prevent references to the database or collections from becoming present in the module level in views or other code. As an added benefit, this ends up being a good way of enforcing separation of concerns so that resources handle database manipulation, and views only translate that for display in the templates.
That error means that your trying to call a method (html) that doesn't exist in the Database instance.
>>> conn = Connection()
>>> db = conn.mydb
>>> col = db.mycoll
>>> col = db.mycoll()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/virtualenvs/myenv/lib/python2.7/site-packages/pymongo-2.0-py2.7-macosx-10.6-x86_64.egg/pymongo/collection.py", line 1156, in __call__
self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'mycoll' method on a 'Database' object it is failing because no such method exists.
If you haven't modified the code then it is possible it's an bug in markupsafe that tries to call html() in a Database instance
s.__html__()

Categories