I have a Flask / Flask-User app that I am trying to convert from Python 3.6 to Flask / Flask-Security-Too under Python 3.10. There have been a lot of changes in the world since 3.6 and I am playing whack-a-mole trying to figure them out. In this particular case I am redoing the database tables since nothing from the old app needs to transfer to the new version. I am using the latest version of PyCharm and all of the latest versions of the libraries that Flask and Flask-Security-Too require.
Things to note: the target database is an MS SQL Server instance. There is an existing "database" that I must use and a specific "schema name" under which any tables I create must live.
I have successfully run flask db init and am trying to run the first flask db migrate but get the error:
(venv) PS C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp> flask db migrate
INFO [alembic.runtime.migration] Context impl MSSQLImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
Traceback (most recent call last):
File "C:\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 988, in main
cli.main()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 579, in main
return super().main(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\decorators.py", line 26, in new_func
return f(get_current_context(), *args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 427, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\cli.py", line 104, in migrate
_migrate(directory, message, sql, head, splice, branch_label, version_path,
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\__init__.py", line 98, in wrapped
f(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\__init__.py", line 155, in migrate
command.revision(config, message, autogenerate=True, sql=sql,
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\command.py", line 229, in revision
script_directory.run_env()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\script\base.py", line 569, in run_env
util.load_python_file(self.dir, "env.py")
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\pyfiles.py", line 94, in load_python_file
module = load_module_py(module_id, path)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\pyfiles.py", line 110, in load_module_py
spec.loader.exec_module(module) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp\migrations\env.py", line 104, in <module>
run_migrations_online()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp\migrations\env.py", line 98, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\runtime\environment.py", line 853, in run_migrations
self.get_context().run_migrations(**kw)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\runtime\migration.py", line 611, in run_migrations
for step in self._migrations_fn(heads, self):
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\command.py", line 205, in retrieve_migrations
revision_context.run_autogenerate(rev, context)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 526, in run_autogenerate
self._run_environment(rev, migration_context, True)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 573, in _run_environment
compare._populate_migration_script(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 55, in _populate_migration_script
_produce_net_changes(autogen_context, upgrade_ops)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 89, in _produce_net_changes
comparators.dispatch("schema", autogen_context.dialect.name)(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\langhelpers.py", line 267, in go
fn(*arg, **kw)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 125, in _autogen_for_tables
[(table.schema, table.name) for table in autogen_context.sorted_tables]
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 443, in sorted_tables
result.extend(m.sorted_tables)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 4697, in sorted_tables
return ddl.sort_tables(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1213, in sort_tables
for (t, fkcs) in sort_tables_and_constraints(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1291, in sort_tables_and_constraints
dependent_on = fkc.referred_table
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 3808, in referred_table
return self.elements[0].column.table
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 2507, in column
raise exc.NoReferencedTableError(
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'roles_users.role_id' could not find table 'role' with which to generate a foreign key to target column 'id'
The User and Role models look like (pruned for length):
### USER
#
import uuid
from flask_security import UserMixin
from sqlalchemy import Column, Integer, String, Boolean, Unicode, DateTime, func
from sqlalchemy.orm import relationship, backref
from app.database import Base
class User(Base, UserMixin):
__tablename__ = 'user'
__table_args__ = {"schema": "ExistingSchemaName"}
id = Column(Integer,primary_key=True)
email = Column(Unicode(255),nullable=False,server_default=u'',unique=True)
...
# Flask-Security-Too fields
fs_uniquifier = Column(String(255), unique=True, nullable=False)
confirmed_at = Column(DateTime())
last_login_at = Column(DateTime())
current_login_at = Column(DateTime())
last_login_ip = Column(String(100))
current_login_ip = Column(String(100))
login_count = Column(Integer)
# Relationships
child_roles = relationship('Role',back_populates='parent_user')
import uuid
### ROLE
#
from flask_security import RoleMixin
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from app.database import Base
class Role(Base, RoleMixin):
__tablename__ = 'role'
__table_args__ = {"schema": "ExistingSchemaName"}
id = Column(Integer(),primary_key=True)
name = Column(String(64),nullable=False,server_default=u'',unique=True)
description = Column(String(255),nullable=False,server_default=u'')
# Have also tried adding schema name to ForeignKey without success, as in:
# user_id = Column(Integer,ForeignKey("ExistingSchemaName.user.id"))
user_id = Column(Integer,ForeignKey("user.id"))
parent_user = relationship("User",back_populates="child_roles")
The app.database.py file looks like:
from .settings import SQLALCHEMY_DATABASE_URI
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(SQLALCHEMY_DATABASE_URI)
db = scoped_session(
sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
)
Base = declarative_base()
Base.query = db.query_property()
def init_db():
import app.models
Base.metadata.create_all(bind=engine)
I think that I have set the one-to-many relationships correctly but I do not know what I am missing.
Related
I'm trying to use Django's factory-bot module to create factories for my models. I'm also using pytest. I have created these factories ...
import factory
from maps.models import CoopType, Coop
from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField
from address.models import State, Country, Locality
class CountryFactory(factory.DjangoModelFactory):
"""
Define Country Factory
"""
class Meta:
model = Country
name = "Narnia"
code = "NN"
class StateFactory(factory.DjangoModelFactory):
"""
Define State Factory
"""
class Meta:
model = State
name = "Narnia"
code = "NN"
country = CountryFactory()
class LocalityFactory(factory.DjangoModelFactory):
"""
Define Locality Factory
"""
class Meta:
model = Locality
name = "Narnia"
postal_code = "60605"
state = StateFactory()
class AddressFactory(factory.DjangoModelFactory):
"""
Define Address Factory
"""
class Meta:
model = Address
street_number = "123"
route = "Rd"
raw = "123 Fake Rd"
formatted = "123 Fake Rd."
latitude = 87.1234
longitude = -100.12342
locality = LocalityFactory()
class CoopTypeFactory(factory.DjangoModelFactory):
"""
Define Coop Type Factory
"""
class Meta:
model = CoopType
I have a very simple test file thus far. It only has one test ...
import pytest
from django.test import TestCase
from .factories import CoopTypeFactory, CoopFactory
class ModelTests(TestCase):
#classmethod
def setUpTestData(cls):
print("setUpTestData: Run once to set up non-modified data for all class methods.")
#management.call_command('loaddata', 'test_data.yaml', verbosity=0)
pass
def setUp(self):
print("setUp: Run once for every test method to setup clean data.")
#management.call_command('flush', verbosity=0, interactive=False)
pass
#pytest.mark.django_db
def test_coop_type_create(self):
""" Test customer model """ # create customer model instance
coop_type = CoopTypeFactory(name="Test Coop Type Name")
assert coop_type.name == "Test Coop Type Name"
But when I run my test, it dies complaining about a duplicate key for a factory that I'm not even creating.
davea$ python manage.py test --settings=maps.test_settings
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: tests.test_models (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_models
Traceback (most recent call last):
File "/Users/davea/Documents/workspace/chicommons/maps/web
...
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 434, in _find_test_path
module = self._get_module_from_name(name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name
__import__(name)
File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_models.py", line 3, in <module>
from .factories import CoopTypeFactory, CoopFactory
File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/factories.py", line 19, in <module>
class StateFactory(factory.DjangoModelFactory):
File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/factories.py", line 28, in StateFactory
country = CountryFactory()
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 46, in __call__
return cls.create(**kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 564, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
return super(DjangoModelFactory, cls)._generate(strategy, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
return step.build()
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/builder.py", line 279, in build
kwargs=kwargs,
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
return self.factory._create(model, *args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 185, in _create
return manager.create(*args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql
cursor.execute(sql, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute
res = self._query(query)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query
db.query(q)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Narnia' for key 'name'")
----------------------------------------------------------------------
Ran 1 test in 0.000s
What am I doing wrong? Why is Django trying to create a factory for something I'm not creating a factory for?
You should use factory.SubFactory for defining foreign key relationships
class LocalityFactory(factory.DjangoModelFactory):
...
state = factory.SubFactory(StateFactory)
Calling the factories in your classes is creating instances
I tried peewee with flask for two days, but I failed till now. The code is as the follows:
import click
from flask import Flask
from flask.cli import FlaskGroup
from playhouse.flask_utils import FlaskDB
from models import *
from config import config
flask_db = FlaskDB()
def create_app(config_name):
application = Flask(__name__)
application.config.from_object(config[config_name])
flask_db.init_app(application)
flask_db.connect_db()
flask_db.database.create_tables([User])
flask_db.database.close()
#application.route('/')
def index():
return "hello world!"
return application
def create_cli_app(info):
return create_app("develop")
#click.group(cls=FlaskGroup, create_app=create_cli_app)
def cli():
pass
#cli.command()
def initdb():
flask_db.connect_db()
flask_db.database.create_tables([User])
flask_db.database.close()
if __name__ == "__main__":
cli()
When I run it with the CLI: python manage.py run, I got the following errors:
(venv) ➜ /Users/yw/Documents/web git:(master) ✗ p manage.py run
Traceback (most recent call last): File "manage.py", line 46, in
cli() File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/core.py",
line 716, in call
return self.main(*args, **kwargs) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/flask/cli.py",
line 345, in main
return AppGroup.main(self, *args, **kwargs) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/core.py",
line 696, in main
rv = self.invoke(ctx) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/core.py",
line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/core.py",
line 889, in invoke
return ctx.invoke(self.callback, **ctx.params) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/core.py",
line 534, in invoke
return callback(*args, **kwargs) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/decorators.py",
line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/click/core.py",
line 534, in invoke
return callback(*args, **kwargs) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/flask/cli.py",
line 388, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) File
"/Users/yw/Documents/web/venv/lib/python3.4/site-packages/flask/cli.py",
line 124, in init
self._load_unlocked() File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/flask/cli.py",
line 148, in _load_unlocked
self._app = rv = self.loader() File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/flask/cli.py",
line 201, in load_app
rv = self.create_app(self) File "manage.py", line 30, in create_cli_app
return create_app("develop") File "manage.py", line 19, in create_app
flask_db.database.create_tables([User]) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/peewee.py",
line 3765, in create_tables
create_model_tables(models, fail_silently=safe) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/peewee.py",
line 5175, in create_model_tables
m.create_table(**create_table_kwargs) File "/Users/yw/Documents/web/venv/lib/python3.4/site-packages/peewee.py",
line 4845, in create_table
if db.sequences and pk is not False and pk.sequence: AttributeError: 'FlaskDB' object has no attribute 'sequences'
Indeed, I just want to initiate the DB by using flask.cli tool. As you see, if I use the command “python manage.py initdb”, I can only get the same error output as above.
So what is the meaning of "'FlaskDB' object has no attribute ‘sequences'"? What should I do?
Thanks for your help!
It seems that your User model doesn't have correct database.
With FlaskDB, your User model should inherit FlaskDB().Model
instead of defining class Meta: database = database.
database = FlaskDB()
class User(database.Model):
pass
I'm trying to launch unittest for my django project and it returns me below error:
ERROR: varys.users.tests.test_all_views (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: varys.users.tests.test_all_views
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "/usr/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
__import__(name)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/users/tests/__init__.py", line 1, in <module>
from .test_all_views import *
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/users/tests/test_all_views.py", line 12, in <module>
from ...urls import urlpatterns
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/urls.py", line 18, in <module>
url(r'^survey/', include('varys.surveys.urls')),
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 26, in include
urlconf_module = import_module(urlconf_module)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/urls.py", line 13, in <module>
from .userrankingreview.views import UserRankingReviewView
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/userrankingreview/views.py", line 6, in <module>
from .forms import UserRankingReviewFormset
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/userrankingreview/forms.py", line 63, in <module>
formfield_callback=formfield_callback
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 981, in inlineformset_factory
FormSet = modelformset_factory(model, **kwargs)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 813, in modelformset_factory
labels=labels, help_texts=help_texts, error_messages=error_messages)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 528, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 282, in __new__
opts.help_texts, opts.error_messages)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/forms/models.py", line 205, in fields_for_model
formfield = formfield_callback(f, **kwargs)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/userrankingreview/forms.py", line 54, in formfield_callback
return field.formfield()
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1263, in formfield
'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/manager.py", line 226, in using
return self.get_queryset().using(*args, **kwargs)
File "/home/antonscherbatov/projects/varys/locus-web-varys-d/varys/surveys/models.py", line 199, in get_query_set
qs = qs.filter(**self.model.subclasses_lookup())
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/polymodels/models.py", line 59, in subclasses_lookup
query_name=query_name
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/polymodels/models.py", line 50, in content_type_lookup
value = [ct.pk for ct in get_content_types(models).values()]
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/polymodels/utils.py", line 26, in get_content_types
return manager.get_for_models(*models, for_concrete_models=False)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 79, in get_for_models
for ct in cts:
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/query.py", line 96, in __iter__
self._fetch_all()
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/home/antonscherbatov/projects/varys/ve/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 451, in execute
return Database.Cursor.execute(self, query, params)
OperationalError: no such table: django_content_type
Yesterday all tests worked well. After checking I noticed that issue is in below code
# forms.py
UserRankingReviewFormset = inlineformset_factory(
UserRankingReviewRequest,
UserRankingReview,
formset=UserRankingInlineFormSet,
extra=0,
can_delete=False,
formfield_callback=formfield_callback
)
where parent_model UserRankingReviewRequest is Proxy model and UserRankingReview model has foreignkey 'request' to UserRankingReviewRequest.
When I set flag Proxy = False for this model then tests work well, but I need this model as Proxy only
any ideas how I can prevent this?
Proxy = True
means that there is no actual database table created for the model. So, when you try to reference the model with a ForeignKey, things break (since the ForeignKey has no db table to point to).
If what you are trying to achieve is to have a "Generic abstract" type object with concrete sub-type and want a foreign-key to any of the sub-types I would recommend checking out https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations (with a custom limit_choices_to on the ForeignKey to ContentType https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to)
You might also be interested in Django Polymorphic (https://django-polymorphic.readthedocs.org/en/latest/) which does all that and more.
If this is happening in tests as it does for me,
maybe this link
can help, in short the answer is:
Ok, I found a way around the problem, in case anyone ever has the same
problem. If you specify TEST_DATABASE_NAME in your settings, it will
force sqllite to use a file database instead of in-memory database,
and then the problem goes.
I'm trying to integrate django-celery into an existing site and I'm coming up against an error that I can't seem to get fixed.
For context, I went through the Django first steps and the test project was successful, ie everything worked as it should.
Now, in my existing project, I can't get the celery worker running from the command line:
manage.py celery worker --loglevel=info --settings=myproject.settings.dev_settings
When i run that I get the following stack trace and error:
Traceback (most recent call last):
File "C:\sites\corecrm\manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 453, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\djcelery\management\commands\celery.py", line 22, in run_from_argv
['%s %s' % (argv[0], argv[1])] + argv[2:],
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 901, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "C:\Python27\lib\site-packages\celery\bin\base.py", line 187, in execute_from_commandline
return self.handle_argv(prog_name, argv[1:])
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 893, in handle_argv
return self.execute(command, argv)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 868, in execute
return cls(app=self.app).run_from_argv(self.prog_name, argv)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 148, in run_from_argv
return self(*args, **options)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 118, in __call__
ret = self.run(*args, **kwargs)
File "C:\Python27\lib\site-packages\celery\bin\celery.py", line 220, in run
return self.target.run(*args, **kwargs)
File "C:\Python27\lib\site-packages\celery\bin\celeryd.py", line 153, in run
return self.app.Worker(**kwargs).run()
File "C:\Python27\lib\site-packages\celery\apps\worker.py", line 162, in run
self.app.loader.init_worker()
File "C:\Python27\lib\site-packages\celery\loaders\base.py", line 130, in init_worker
self.import_default_modules()
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 138, in import_default_modules
self.autodiscover()
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 141, in autodiscover
self.task_modules.update(mod.__name__ for mod in autodiscover() or ())
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 176, in autodiscover
for app in settings.INSTALLED_APPS])
File "C:\Python27\lib\site-packages\djcelery\loaders.py", line 195, in find_related_module
return importlib.import_module('%s.%s' % (app, related_name))
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\sites\corecrm\people\tasks.py", line 15, in <module>
from people.models import Customer, CustomerCsvFile, CustomerToTag, get_customer_from_csv_row
File "C:\sites\corecrm\people\models.py", line 163, in <module>
UserProfile._meta.get_field_by_name('username')[0]._max_length = 75
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 351, in get_field_by_name
cache = self.init_name_map()
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 380, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 469, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "C:\Python27\lib\site-packages\django\db\models\options.py", line 483, in _fill_related_many_to_many_cache
for klass in get_models(only_installed=False):
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 197, in get_models
self._populate()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 75, in _populate
self.load_app(app_name)
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
File "C:\sites\corecrm\booking\models.py", line 17, in <module>
from people.models import Customer, UserProfile
ImportError: cannot import name Customer
To try and work out what the booking/models.py script sees in people I added the following at the start:
import people
print 'path: %s' % people.__path__
for item in dir(people):
print item
and that gives me the following output:
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
however, when I run manage.py shell --settings=myproject.settings.dev_settings I get the following output:
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
path: ['C:\\sites\\corecrm\\people']
__builtins__
__doc__
__file__
__name__
__package__
__path__
models
As you can see the models module is available at the end of the 2nd list for the shell command (and I've confirmed this is also the case for manage.py commands other than celery). How would I make sure that module is available at the same point when I run the celery command?
EDIT: I've now also set up this project on an Ubuntu VM and I'm getting the same error when I try to run the worker manage command. Any ideas? Anyone?
ANOTHER EDIT: I've pasted the code for booking/models.py and people/models.py at http://pastebin.com/fTVVBtB4
I'm pretty sure this line is your problem:
File "C:\sites\corecrm\people\models.py", line 163, in <module>
UserProfile._meta.get_field_by_name('username')[0]._max_length = 75
While you're still busy importing from people.models, this line (in particular get_field_by_name) forces Django to evaluate the model and setup all relationships between that model and it's related models. This, in turn, forces an import of Customer in people.models, while you're still busy importing that exact model. This is what results in an ImportError.
For a working solution you'll need to post your models.py.
Why does this error only occur with celery? I can't say for sure without some more information, but my best guess is that Celery handles importing everything slightly different (Django probably doesn't import Customer, CustomerCsvFile, CustomerToTag and get_customer_from_csv_row all at once) and that this exposes the bug in your code.
EDIT/SOLUTION:
I would remove this line:
UserProfile._meta.get_field_by_name('username')[0]._max_length = 75
And move it to the instance level, into the __init__ method:
class UserProfile(AbstractUser):
def __init__(self, *args, **kwargs):
self._meta.get_field_by_name('username')[0]._max_length = 75
super(UserProfile, self).__init__(*args, **kwargs)
If the cause of the issue is indeed what I think it is, this will fix the circular import while providing the same functionality. If the max_length functionality gets broken somehow (most likely because internally a max_length validator is added to CharField and _max_length is changed too late) I would instead override the complete username field in the init method:
class UserProfile(AbstractUser):
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self._meta.get_field_by_name('username')[0] = models.CharField(max_length=75, etc.)
I'm trying to create an admin user as part of my tests.py to check on persmissions.
UPDATE:
The tests.py is standard format that subclasses TestCase and the code below is called in the setUp() function.
I can create a normal user but not an admin user. If I try this:
self.adminuser = User.objects.create_user('admin', 'admin#test.com', 'pass')
self.adminuser.save()
self.adminuser.is_staff = True
self.adminuser.save()
OR
self.adminuser = User.objects.create_superuser('admin', 'admin#test.com', 'pass')
self.adminuser.save()
I get:
Warning: Data truncated for column 'name' at row 1
If I remove the is_staff line all is well (except I can't do my test!)
Do I have to load admin users as fixtures?
UserProfile is defined as follows:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
organisation = models.ForeignKey(Organisation, null=True, blank=True)
telephone = models.CharField(max_length=20, null=True, blank=True)
and full error traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 242, in __call__
self._pre_setup()
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 217, in _pre_setup
self._fixture_setup()
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 440, in _fixture_setup
return super(TestCase, self)._fixture_setup()
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 222, in _fixture_setup
call_command('flush', verbosity=0, interactive=False)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/__init__.py", line 166, in call_command
return klass.execute(*args, **defaults)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/commands/flush.py", line 61, in handle_noargs
emit_post_sync_signal(models.get_models(), verbosity, interactive)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/sql.py", line 205, in emit_post_sync_signal
interactive=interactive)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/dispatch/dispatcher.py", line 166, in send
response = receiver(signal=self, sender=sender, **named)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/contrib/auth/management/__init__.py", line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 123, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 335, in get_or_create
obj.save(force_insert=True)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 410, in save
self.save_base(force_insert=force_insert, force_update=force_update)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 495, in save_base
result = manager._insert(values, return_id=update_pk)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 177, in _insert
return insert_query(self.model, values, **kwargs)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 1087, in insert_query
return query.execute_sql(return_id)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/subqueries.py", line 320, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/backends/mysql/base.py", line 84, in execute
return self.cursor.execute(query, args)
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 175, in execute
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 89, in _warning_check
File "/usr/lib64/python2.4/warnings.py", line 61, in warn
warn_explicit(message, category, filename, lineno, module, registry)
File "/usr/lib64/python2.4/warnings.py", line 96, in warn_explicit
raise message
Warning: Data truncated for column 'name' at row 1
The answer seems to be that you can't create an admin user in setUp but you can in any other function so if you want an admin user in testing, use a fixture!
I'd use the built-in create_superuser and log the user in before making any requests. The following should work:
from django.contrib.auth.models import User
from django.test.client import Client
# store the password to login later
password = 'mypassword'
my_admin = User.objects.create_superuser('myuser', 'myemail#test.com', password)
c = Client()
# You'll need to log him in before you can send requests through the client
c.login(username=my_admin.username, password=password)
# tests go here
Update 2
Executed the snippet to create the superuser from within a test case (subclass of django.test.TestCase). Everything went fine. Also created and saved an instance of UserProfile with user = self.adminuser. That too worked.
Update
This line is interesting:
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/contrib/auth/management/__init__.py", line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
Looks like execution fails when creating permissions.
Original Answer
Warning: Data truncated for column 'name' at row 1
Strange. I tried this from the Django shell and it worked for me. I am using Postgresql 8.3 and Django 1.2.1 on Ubuntu Jaunty. Can you give more details about which version of Django/database are you using?
Also User does not have a name attribute. Can you double check if you are using auth.User?
Do I have to load admin users as fixtures?
You don't have to. But if you are creating this admin user solely for testing purposes then it would be a good idea to add a Fixture. That is what I do in my projects.