Django with MSSQL giving error :'DatabaseWrapper' object has no attribute 'Database' - python

I am newbie to python and djanog.
I install django using.
Pip install django
Than I installed Mssql connector.
pip install django-mssql
than I run syncdb using this command.
python manage.py syncdb
It shows all tables are created but I didn't see any table in sql server management studio.
After that I tried to open Admin panal using http:// 127.0.0.1:8000/admin
it gives error.
ERROR
'DatabaseWrapper' object has no attribute 'Database'
Following is error:
Request Method: GET
Request URL: http:// 127.0.0.1:8000/admin
Django Version: 1.6.1
Exception Type: AttributeError
Exception Value: 'DatabaseWrapper' object has no attribute 'Database'
Exception Location: C:\Python27\lib\site-packages\django\db\utils.py in __exit__, line 86
Python Executable: C:\Python27\python.exe
Python Version: 2.7.6
SETTING.PY
DATABASES = {
'default': {
'NAME': 'dbexp',
'ENGINE': 'sqlserver_ado',
'HOST': '172.16.26.51\instance',
'USER': '****',
'PASSWORD': '******',
}
}
STACK TRACE
Environment:
Request Method: GET
Request URL: http: //127.0.0.1:8000/admin/
Django Version: 1.6.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in wrapper
215. return self.admin_view(view, cacheable)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
192. if not self.has_permission(request):
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in has_permission
143. return request.user.is_active and request.user.is_staff
File "C:\Python27\lib\site-packages\django\utils\functional.py" in inner
213. self._setup()
File "C:\Python27\lib\site-packages\django\utils\functional.py" in _setup
298. self._wrapped = self._setupfunc()
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in <lambda>
18. request.user = SimpleLazyObject(lambda: get_user(request))
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in get_user
10. request._cached_user = auth.get_user(request)
File "C:\Python27\lib\site-packages\django\contrib\auth\__init__.py" in get_user
140. user_id = request.session[SESSION_KEY]
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\base.py" in __getitem__
47. return self._session[key]
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session
173. self._session_cache = self.load()
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\db.py" in load
20. expire_date__gt=timezone.now()
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in get
151. return self.get_queryset().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
301. num = len(clone)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in __len__
77. self._fetch_all()
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _fetch_all
854. self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django\db\models\query.py" in iterator
220. for row in compiler.results_iter():
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
710. for rows in self.execute_sql(MULTI):
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
781. cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
69. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
53. return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
86. db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
Exception Type: AttributeError at /admin/
Exception Value: 'DatabaseWrapper' object has no attribute 'Database'

For me I installed both django and django-mssql with pip. django was version 1.6 and django-mssql was version 1.4.
From the docs:
The current version of django-mssql supports Django 1.6.
django-mssql 1.4 supports Django 1.4 and 1.5.
I solved the problem with installing django-mssql from source. Download the source from bitbucket.
https://bitbucket.org/Manfre/django-mssql/get/default.zip or clone it with mercurial.
Then run the below command to install
> python setup.py install
Now check the version of django-mssql
> python
>>> import sqlserver_ado
>>> sqlserver_ado.__version__
u'1.5a'

I am not much aware of Django, but, I know SQL Server. From the connection file below:
'default': {
'NAME': 'dbexp',
'ENGINE': 'sqlserver_ado',
'HOST': '172.16.26.51\instance',
'USER': '****',
'PASSWORD': '******',
}
I assume dbexp is the database name, sqlserver_ado is the database Engine name, which is also the Instance name. So, the Engine should be sqlserver_ado\instance and the actual host name is either the [computer name]/IP(172.16.26.51).

Related

Django Social Login: 'AsgiRequest' object has no attribute 'session'

Got an error when trying social-app-django (2.1.0), the error thrown was:
'AsgiRequest' object has no attribute 'session'
Running with channels 1.1.8, Django 2.0.3, asgi-redis 1.2.0, python 3.6
Running via python manage.py runserver (development environment) not uwgsi or nginx.
The occurs when trying to access /social/login/google-oauth2/ (authenticating with google account).
I have read about changing MIDDLEWARE_CLASSES to MIDDLEWARE but we have been using Django >=1.9 for a while so it has already been changed.
The traceback looks as follows:
Traceback (most recent call last):
File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35,in inner
response = get_response(request)
File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/lib/python3.6/site-packages/channels/handler.py", line 243, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/lib/python3.6/site-packages/social_django/utils.py", line 38, in wrapper
request.social_strategy = load_strategy(request)
File "/lib/python3.6/site-packages/social_django/utils.py", line 23, in load_strategy
return get_strategy(STRATEGY, STORAGE, request)
File "/lib/python3.6/site-packages/social_core/utils.py", line 279, in get_strategy
return Strategy(Storage, *args, **kwargs)
File "/lib/python3.6/site-packages/social_django/strategy.py", line 39, in init
self.session = request.session if request else {}
AttributeError: 'AsgiRequest' object has no attribute 'session'
Middleware is the following (added because other WsgiRequest has no attribute session have been related with middleware):
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.auth.middleware.SessionAuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.middleware.security.SecurityMiddleware",
"social_django.middleware.SocialAuthExceptionMiddleware",
"django.middleware.cache.UpdateCacheMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.cache.FetchFromCacheMiddleware",
]
The problem was with middleware. I upgraded from Django>=1.9 to 2.0.3. SessionAuthenticationMiddleware was removed. When debugging middleware I found this:
ImportError: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class
The solution was to removed it. The reason why didn't it logged it out before it is unknown.
You can read more about this here:
SessionAuthenticationMiddleware removed release notes

Django -- Models don't exist, but Django still loads them

Im getting a ProgrammingError when I try to delete a User object, this is wherever User.delete occurs, it even happens in the admin.
The Error
Django apparently 'thinks' that there's a relationship between auth_user and apiHandlers_cardholders which doesn't exist anywhere, the database doesn't have a column for this, and there is no models.[y nor admin.py in the app named apiHandlers , but Django expects it to, there is even a section of the Admin site devoted to it. This only started happening when I migrated from SQLite to PostGreSQL.
At the moment all the local dependencies (models, admin, forms and fields) are in an app called helpers, I'm not sure if this is efficient, but it keeps everything in one place and avoids complications.
UPDATE 0.1
No. One of the probably gonna be many updates
I used to have a problem when migrating, related to Django Rest Framework, but I eventually managed to fix it by a quick pip install to a new update of restframework, it's no longer giving me any error while making migrations and migrating.
Below is the current traceback I'm getting from the Django admin, it's basically the same in the other deletion methods.
`
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/auth/user/3/delete/
Django Version: 1.9.2
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'oauth2_provider',
'apiHandlers',
'frontEnd',
'helpers',
'nonUser']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware']
Traceback:
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
541. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/utils/decorators.py" in inner
184. return func(*args, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in delete_view
1629. [obj], opts, request.user, self.admin_site, using)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/contrib/admin/utils.py" in get_deleted_objects
128. collector.collect(objs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/contrib/admin/utils.py" in collect
193. return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/models/deletion.py" in collect
230. elif sub_objs:
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/models/query.py" in __nonzero__
266. return type(self).__bool__(self)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/models/query.py" in __bool__
262. self._fetch_all()
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
1074. self._result_cache = list(self.iterator())
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
52. results = compiler.execute_sql()
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
848. cursor.execute(sql, params)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/utils.py" in __exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/Mason/Documents/dev/FlowFrameWork/flow-framework/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /admin/auth/user/3/delete/
Exception Value: relation "apiHandlers_cardholder" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "apiHandle...
^
`
UPDATE 0.2
I am using ./manage.py runserver (Mac) to run it, so far I haven't managed to test it with Nginx and WSGI on my server.
I am not getting a warning saying that it could affect another model, in the admin, for example, I am just getting this error immediately.
This is very likely to be because you have a stray models.pyc file somewhere. Clear out all the *.pyc files. You can try something like this if you are on linux:
find . -name '*pyc' -exec 'rm' '{}' ';'
Follow that by ./manage.py makemigrations apihandlers and then ./manage.py migrate

django 1.7 admin: 'ModelMultipleChoiceField' object has no attribute 'limit_choices_to'

I'm working on a legacy django 1.4 project, porting it to django 1.7.
When accessing the django admin interface, in order to show user data I get the aforementioned error.
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/auth/user/1/
Django Version: 1.7.4
Python Version: 2.7.8
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.humanize',
'simple_autocomplete',
'paypal.standard.ipn',
'sorl.thumbnail',
'haystack',
'crispy_forms',
'siteprefs',
'sitegate',
'debug_toolbar',
'modeltranslation',
'rosetta',
# omitted: some project-specific apps
)
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "MYENV/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
583. return self.admin_site.admin_view(view)(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
206. return view(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
1456. return self.changeform_view(request, object_id, form_url, extra_context)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "MYENV/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1419. form = ModelForm(instance=obj)
File "MYENV/lib/python2.7/site-packages/django/contrib/auth/forms.py" in __init__
145. super(UserChangeForm, self).__init__(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/forms/models.py" in __init__
333. limit_choices_to = formfield.get_limit_choices_to()
File "MYENV/lib/python2.7/site-packages/django/forms/models.py" in get_limit_choices_to
1126. if callable(self.limit_choices_to):
Exception Type: AttributeError at /admin/auth/user/1/
Exception Value: 'ModelMultipleChoiceField' object has no attribute 'limit_choices_to'
The self object in the offending line is a django.forms.models.ModelMultipleChoiceField instance (of course), the formfield in line 333 (see traceback) is instantiated as formfield = self.fields['groups'].
The error raises even on an empty db (with just one user). I've checked twice but there are no changes in the AUTH_MODEL, in the signals or any OneToOne link to the User model.
I've checked also the external apps for similar issues without any luck. Does anybody had the same issue in the past and can give me an hint on where to search for the source of this error? I'm still reluctant to report a bug to django since I cannot replicate it if I'm unable to define where the error is triggered.
EDIT:
I've verified that the problem arises in every model that has a foreign key (or a M2M, or a O2O). #Alasdair comment was a good suggestion but for sure I do not alter the queryset in all the models so the reason should be elsewhere.
I suggest you try disabling simple_autocomplete. There appears to be a similar issue with django-ajax-selects.

Error in import FloatField, using django-import-export

I am using django-import-export for import csv file. I have a FloatField in my model :
models.py
purchase_price = models.FloatField(null=True, blank=True)
When I import csv file with blank value, it throws an error :
ValueError at /admin/csv_imp/book/process_import/
could not convert string to float:
Request Method: POST
Request URL: http://localhost:8000/admin/csv_imp/book/process_import/
Django Version: 1.7.1
Exception Type: ValueError
Exception Value:
could not convert string to float:
Exception Location: /home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1550
Python Executable: /home/bgdev/Desktop/virtualenvs/django17/bin/python
Python Version: 2.7.6
Python Path:
['/home/bgdev/Desktop/virtualenvs/django17/test_pro',
'/home/bgdev/Desktop/virtualenvs/django17/src/admin-bootstrap',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/plat-i386-linux-gnu',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-tk',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-old',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/site-packages']
Server time: Tue, 9 Dec 2014 05:33:36 +0000
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/csv_imp/book/process_import/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('bootstrap_admin',
'import_export',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'csv_imp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
204. return view(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/admin.py" in process_import
130. raise_errors=True)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in import_data
359. six.reraise(*sys.exc_info())
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in import_data
345. self.save_instance(instance, real_dry_run)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in save_instance
163. instance.save()
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in save
591. force_update=force_update, update_fields=update_fields)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
619. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
681. forced_update)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_update
725. return filtered._update(values) > 0
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/query.py" in _update
600. return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1004. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
775. sql, params = self.as_sql()
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
969. val = field.get_db_prep_save(val, connection=self.connection)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
627. prepared=False)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
619. value = self.get_prep_value(value)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
1550. return float(value)
Exception Type: ValueError at /admin/csv_imp/book/process_import/
Exception Value: could not convert string to float:
I found similar issue with and IntegerField. Being the last column in the csv file, it turns out that I was introducing an extra End of Line character in the dataset, even if the field had an empty value. Removing the EOL character from every line before adding it to the dataset fixed the issue:
for line in file.readlines():
line = line.rstrip('\r\n')
dataset.append(tuple(item for item in line.split(',')))
This link will show you what null and blank do: differentiate null=True, blank=True in django
If you can arrange your csv file to have all of the null values at the end, you can just remove the commas. That might work. Or perhaps create a temporary model that assigns those fields to a Charfield. Then copy appropriate fields to your final model
This is untested:
update <table> set <field> = 0 where id in (select id from <table> where <field> = "");
Fill in your table name and the field name as appropriate. You can run this from your sql command line program

Django: FieldError cannot resolve keyword '___' into a field

I'm having a FieldError.
I have a model:
class Foo(models.Model):
__bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True)
def get_bar(self):
return cPickle.loads(str(self.__bar))
def set_bar(self, values):
self.__bar = cPickle.dumps(values)
bar = property(get_bar, set_bar)
I have registered it with the admin in admin.py:
admin.site.register(Foo)
When I runserver and go to /admin, I see Foo in the list. If I click "Add", it works fine, showing the form to add a new Foo. However, if I click "save and add another" or "change" or "Foos", I get a FieldError
FieldError at /admin/appname/Foo/
Cannot resolve keyword '_Foo' into field. Choices are: _Foo__bar, appname
The traceback is:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/appname/foo/
Django Version: 1.2.4
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'pagination',
'apps.appname']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in wrapper
265. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
78. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
190. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapper
21. return decorator(bound_func)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in bound_func
17. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in changelist_view
1097. 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in __len__
80. self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in iterator
271. for row in compiler.results_iter():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in results_iter
677. for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
722. sql, params = self.as_sql()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in as_sql
57. ordering, ordering_group_by = self.get_ordering()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in get_ordering
346. self.query.model._meta, default_order=asc):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in find_ordering_name
375. opts, alias, False)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in setup_joins
1215. "Choices are: %s" % (name, ", ".join(names)))
Exception Type: FieldError at /admin/appname/foo/
Exception Value: Cannot resolve keyword '_Foo' into field. Choices are: _Foo__bar, appname
What could be going on here? I did some searching, and I found similar errors but they seem to have something to do with many-to-many fields, of which I have none. There are other models that reference this one as a foreign key, but that seems unlikely to cause the problem.
Because you've prefixed __bar with two underscores, Python is performing name mangling (doc link) in an attempt to enforce private access to the variable.
Private variables, of course, don't exist in Python, but by using the double-underscore convention you've asked Python to reformat __bar as _(classname)__bar, which is why Django is telling you that "Choices are: _Foo__bar...".
If you wish to signal that bar shouldn't be used outside out the class, I'd recommend the single-underscore notation (also discussed at the link above), which should solve the field issue you're experiencing as single-underscore prefixes are not name mangled.

Categories