DB constantly exploding in Django - python

I am trying to get going with django, which so far I have found to be amazing other than repeated db issues.
My latest is following the Django by Example book and I have followed everything to the letter, yet when following some simple instructions to add some data via the python shell api I get the following:
>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='jamie')
>>> Post.objects.create(title='One More Post', slug='one-more-post', body='Post body', author='user')
Traceback (most recent call last):
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/base.py", line 468, in __init__
setattr(self, field.name, rel_obj)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 629, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "'user'": "Post.author" must be a "User" instance.
This has happened while following multiple tutorials and I am stumped. I followed standard instructions and installed, pip, python and django via terminal. Also using a virtual env so not sure why this is happening.

Use this instead of your statement.
Use user variable instead of 'user' string.
Post.objects.create(title='One More Post', slug='one-more-post',
body='Post body', author=user)

Related

Chatterbot installation working, but broken calls to variables

I installed chatterbot in my terminal earlier today using virtual studio code's terminal. I saw that both chatterbot and chatterbot_corpus worked in installation. Then, I made the following python document:
EDIT: Turns out I should define a chatbot variable first.
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer
conversation = [
"Hello",
"Hi there!",
"How are you doing?",
"I'm doing great.",
"That is good to hear",
"Thank you.",
"You're welcome."
]
bot = ChatBot('Maya')
trainer = ListTrainer(bot)
trainer.train(conversation)
This was my code
it says this however
bot = ChatBot('Maya')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\chatterbot.py", line 34, in __init__
self.storage = utils.initialize_class(storage_adapter, **kwargs)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\utils.py", line 54, in initialize_class
return Class(*args, **kwargs)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\storage\sql_storage.py", line 22, in __init__
from sqlalchemy import create_engine
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\__init__.py", line 8, in <module>
from . import util as _util # noqa
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\util\__init__.py", line 14, in <module>
from ._collections import coerce_generator_arg # noqa
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\util\_collections.py", line 16, in <module>
from .compat import binary_types
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\util\compat.py", line 264, in <module>
time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'
Does anyone know how to fix this easily?
EDIT: I just updated python using pip install --upgrade ipython in terminal, but it didn't fix the issue
EDIT 2: Well now I tried updating a package using pip install sqlalchemy --upgrade
But now it gives
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\chatterbot.py", line 34, in __init__
self.storage = utils.initialize_class(storage_adapter, **kwargs)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\utils.py", line 54, in initialize_class
return Class(*args, **kwargs)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\storage\sql_storage.py", line 46, in __init__
if not self.engine.dialect.has_table(self.engine, 'Statement'):
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\dialects\sqlite\base.py", line 2009, in has_table
self._ensure_has_table_connection(connection)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\engine\default.py", line 341, in _ensure_has_table_connection
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: The argument passed to Dialect.has_table() should be a <class 'sqlalchemy.engine.base.Connection'>,
got <class 'sqlalchemy.engine.base.Engine'>. Additionally, the Dialect.has_table() method is for internal dialect use only; please use ``inspect(some_engine).has_table(<tablename>>)`` for public API use.
I am in the latest version though
PS C:\Users\Subha> Python --version
Python 3.9.6
EDIT 3: Now it comes up with
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\chatterbot.py", line 34, in __init__
self.storage = utils.initialize_class(storage_adapter, **kwargs)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\utils.py", line 54, in initialize_class
return Class(*args, **kwargs)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\chatterbot\storage\sql_storage.py", line 46, in __init__
# if not self.engine.dialect.has_table(self.engine, 'Statement'):
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\dialects\sqlite\base.py", line 2009, in has_table
self._ensure_has_table_connection(connection)
File "C:\Users\Subha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\sqlalchemy\engine\default.py", line 341, in _ensure_has_table_connection
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: The argument passed to Dialect.has_table() should be a <class 'sqlalchemy.engine.base.Connection'>, got <class 'sqlalchemy.engine.base.Engine'>. Additionally, the Dialect.has_table() method is for internal dialect use only; please use ``inspect(some_engine).has_table(<tablename>>)`` for public API use.
it seems the python upgrade worked with regard to the initial error on time.clock. This new error you are seeing is quite different to the previous one. In this case you need to go into chatterbot/storage/sql_storage.py and comment out if not self.engine.dialect.has_table(self.engine, 'Statement'): and leave only self.create_database(). This means that instead of checking whether a database table has been created which is triggering the error, it will just create the DB every time, which i expect to work fine.
# if not self.engine.dialect.has_table(self.engine, 'Statement'):
self.create_database()

Official Softlayer script to retrieve locations ids does not work

I used to use the following script for retrieving the different locations ids, to create an VSI order:
https://softlayer.github.io/python/list_packages/
Specifically:
def getAllLocations(self):
mask = "mask[id,locations[id,name]]"
result = self.client['SoftLayer_Location_Group_Pricing'].getAllObjects(mask=mask);
pp(result)
Unfortunately meanwhile it throws the following exception:
Traceback (most recent call last):
File "new.py", line 59, in <module>
main.getAllLocations()
File "new.py", line 52, in getAllLocations
result = self.client['SoftLayer_Location_Group_Pricing'].getAllObjects(mask=mask);
File "/usr/local/lib/python2.7/site-packages/SoftLayer/API.py", line 392, in call_handler
return self(name, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/API.py", line 360, in call
return self.client.call(self.name, name, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/API.py", line 263, in call
return self.transport(request)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/transports.py", line 195, in __call__
raise _ex(ex.faultCode, ex.faultString)
SoftLayer.exceptions.SoftLayerAPIError: SoftLayerAPIError(SOAP-ENV:Server): Internal Error
Is there something that needs to be changed within the function?
Nope your code is fine the problem is that this is an issue with the method which is not working I am gonna report the issue or if you want it you can open an softlayer's ticket and report the issue yourself.
An issue with the getAllObjects method was fixed yesterday for this service. Please try the request again.

Python code not working from cron job but works from command line via virtualenv

I am receiving different errors which I cannot determine the issue. It seems as though it has to do with the configparser.py NoSectionError(section). This code runs fine from the command line in the virtualenv.
Traceback (most recent call last):
File "/usr/lib/python3.5/configparser.py", line 1135, in _unify_values
sectiondict = self._sections[section]
KeyError: 'token'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/lvensel/projects/worklion01/worklion01/wl_cron.py", line 15, in <module>
wl_post_projects.post()
File "/home/lvensel/projects/worklion01/worklion01/wl_post_projects.py", line 15, in post
import wl_get_background_jobs
File "/home/lvensel/projects/worklion01/worklion01/wl_get_background_jobs.py", line 12, in <module>
oauth, token = wl_secure_token.fetch_token()
File "/home/lvensel/projects/worklion01/worklion01/wl_secure_token.py", line 17, in fetch_token
values = wl_get_ini.get_values()
File "/home/lvensel/projects/worklion01/worklion01/wl_get_ini.py", line 13, in get_values
'token_url': config.get('token', 'token_url'),
File "/usr/lib/python3.5/configparser.py", line 778, in get
d = self._unify_values(section, vars)
File "/usr/lib/python3.5/configparser.py", line 1138, in _unify_values
raise NoSectionError(section)
configparser.NoSectionError: No section: 'token'
Let me guess on what potentially happens:
Cron jobs are run by root
virtualenv is run by your user with a custom python environment.
root does not know about your virtualenv, then cannot match your user's python environment, thus your script fails. Probably with some cannot import or alike errors.
Have a look at replies here.

Exceptions using django standalone with python3

Trying to use django templates in stand-alone mode.
I get these exceptions (below).
New to python, wondering if anyone would be willing to help out.
Django is used for templating in a script which is not shown here.
However the exact same exceptions appear when launching it.
>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 86, in __getitem__
return self._engines[alias]
KeyError: 'django'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/django/template/base.py", line 182, in __init__
engine = Engine.get_default()
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/usr/local/lib/python3.4/dist-packages/django/template/engine.py", line 88, in get_default
django_engines = [engine for engine in engines.all()
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 110, in all
return [self[alias] for alias in self]
....
....
File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
My django version:
python3 -c "import django; print(django.get_version())" ---> 1.9.7
My python version:
Python 3.4.3
After calling settings.configure(), you must call django.setup().
import django
from django.conf import settings
settings.configure()
django.setup()
from django.template import Template, Context
t = Template('My name is {{ my_name }}.')
c=Context({'my_name': 'Mindaugas'})
t.render(c)
See the docs for more info.

Django does not allow to get/create new object: QuerySet object has no attribute get_or_create

I am using Python 3.2 with Django 1.6.2 on PostgreSQL
When trying to conditionally create object using get_or_create shortcut, I get AttributeError.
Of course, the workaround would be to catch the exception when trying to get the object and then create it. But can it be done using regular get_or_create?
'QuerySet' object has no attribute 'get_or_create'
Traceback (most recent call last):
File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 195, in wrapper
response = callback(request, *args, **kwargs)
File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 426, in dispatch_list
return self.dispatch('list', request, **kwargs)
File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 458, in dispatch
response = method(request, **kwargs)
File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 1320, in post_list
updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
File "/Users/urk/Documents/xxx/app/api/userresource.py", line 51, in obj_create
api_key, created = ApiKey.objects.get_or_create(user=rv.obj)
File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/django/db/models/manager.py", line 154, in get_or_create
return self.get_queryset().get_or_create(**kwargs)
AttributeError: 'QuerySet' object has no attribute 'get_or_create'
EDIT: Code sample.
The following code from python manage.py shell gives the exception
from django.contrib.auth.models import User
User.objects.get_or_create(username='tu')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/django/db/models/manager.py", line 154, in get_or_create
return self.get_queryset().get_or_create(**kwargs)
AttributeError: 'QuerySet' object has no attribute 'get_or_create'
Recreating virtual environment as suggested by #AndreyNelubin solved the problem.

Categories

Resources