Django-parler unique_together constraint between translated and normal field - python-3.x

I want to make unique_together constraint with django-parler between translated field and normal field.
I'd like to do this:
class Part(TranslatableModel):
code = CharField('code')
translations = TranslatedFields(
name = CharField('name')
)
class Meta:
constraints = [
UniqueConstraint(
fields=['code', 'name'],
name='constraint_name',
)
]
but then I get error:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_from_command_line(sys.argv)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle
fake_initial=fake_initial,
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 827, in database_forwards
schema_editor.add_constraint(model, self.constraint)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 405, in add_constraint
self._remake_table(model)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 279, in _remake_table
self.create_model(new_model)
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 296, in create_model
constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints]
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 296, in <listcomp>
constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints]
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/models/constraints.py", line 89, in constraint_sql
fields = [model._meta.get_field(field_name).column for field_name in self.fields]
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/models/constraints.py", line 89, in <listcomp>
fields = [model._meta.get_field(field_name).column for field_name in self.fields]
File "/home/lauri/työt/p/venv/lib/python3.6/site-packages/django/db/models/options.py", line 567, in get_field
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: NewPart has no field named 'name'
I'm not very aware of insides of django-parler so I'm not able to move forward with this.

When you make migrations there will be two tables Part and PartTranslation. What you want is single translation for single post. So the following lines solves your problem
translations = TranslatedFields(
name = CharField('name'),
meta={'unique_together': [('name', 'language_code')]}
)
For uniqueness of Parts just make the code field unique.
code = CharField('code', unique=True)

Related

ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value

I have a Django cookiecutter template. After performing all the required actions given on cookiecutter docs when I run python manage.py migrate I get this error
Traceback (most recent call last):
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\task_manager_app\manage.py", line 31, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
self.check(databases=[database])
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 419, in check
all_issues = checks.run_checks(
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models
errors.extend(model.check(**kwargs))
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 1303, in check
*cls._check_indexes(databases),
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 1695, in _check_indexes
connection.features.supports_covering_indexes or
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\postgresql\features.py", line 93, in is_postgresql_11
return self.connection.pg_version >= 110000
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\postgresql\base.py", line 329, in pg_version
with self.temporary_connection():
File "C:\Python310\lib\contextlib.py", line 135, in __enter__
return next(self.gen)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\base\base.py", line 603, in temporary_connection
with self.cursor() as cursor:
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
return self._cursor()
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor
self.ensure_connection()
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
self.connect()
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\base\base.py", line 199, in connect
conn_params = self.get_connection_params()
File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\postgresql\base.py", line 157, in get_connection_params
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value.
This is the settings base.py file (database setting part) which come by default with template
DATABASES = {
"default": env.db(
"DATABASE_URL",
default="postgres://localhost/task_manager_app",
),
}
DATABASES["default"]["ATOMIC_REQUESTS"] = True
I've set the database URL using command
export DATABASE_URL=postgres://postgres:mypass#127.0.0.1:5432/task_manager_app
Anyone help me out to get rid of this error.
First of all you have to do it as follows:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql', #Make sure you have psycopg2 installed. It is postgresql connector.
'NAME': ‘DB NAME’,
'USER': 'DB USERNAME',
'PASSWORD': 'USER PASSWORD',
'HOST': 'HOST IP',
'PORT': 'PORT',#Generally 5432
}
}
After puzzling over it a lot, I got the solution. The problem was having the character "#" in my database password.

wagtail: Locale_ID cannot be null

I'm trying to deploy a website with wagtail 2.11 on pythonanywhere. However, I'm unable to save any page models in the frontend.
The cause seems to be that in my 'home'-app, migration 0002_create_homepage.py cannot be not applied. Trying so gives me this error (IntegrityError: (1048, "Column 'locale_id' cannot be null")):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle
post_migrate_state = executor.migrate(
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/migration.py", line 121, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
self.code(from_state.apps, schema_editor)
File "/home/yogagarten/yogagarten.pythonanywhere.com/home/migrations/0002_create_homepage.py", line 21, in create_homepage
homepage = HomePage.objects.create(
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 789, in save_base
parent_inserted = self._save_parents(cls, using, update_fields)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 818, in _save_parents
updated = self._save_table(
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
return manager._insert(
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sq
l
cursor.execute(sql, params)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wra
ppers
return executor(sql, params, many, context)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 78, in execute
raise IntegrityError(*tuple(e.args))
django.db.utils.IntegrityError: (1048, "Column 'locale_id' cannot be null")
My settings.py
INSTALLED_APPS = [
'wagtail.locales',
]
LANGUAGE_CODE = 'de-DE'
LANGUAGES = [('de', 'German'),]
WAGTAILADMIN_PERMITTED_LANGUAGES = [('de', 'German'),]
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Basic model example:
class HomePage(Page):
template = 'home/index.html'
ueberschrift = models.CharField(max_length=60, blank=False, null=True)
content_panels = ([FieldPanel('ueberschrift')])
class Meta:
verbose_name = 'Startseite'
I haven't created any page objects yet.
Can you give me some advice on how to fix this error? I understand that every page model comes with a locale field. But I don't know what to do with that info.
What I've tried:
redid everything with a new database
reset the language settings to default (en-us)
I tried the run_before command.
I checked this answer and followed this part of
the official documentation
I'm using wagtail 2.11 with django 3.1.3 and python 3.8.
Thanks so much!
You need to add the following line to the 0002_create_homepage.py migration file, inside class Migration:
run_before = [
('wagtailcore', '0053_locale_model'),
]
This change is necessary as a result of the new multi-language implementation in Wagtail 2.11. More details are here: https://docs.wagtail.io/en/stable/releases/2.11.html#run-before-declaration-needed-in-initial-homepage-migration
If you've already run ./manage.py migrate without this new line in place and received the locale_id IntegrityError, you'll need to drop and recreate the database and then re-run ./manage.py migrate, as the previous failure will have left the database in an inconsistent state. (Dropping and recreating the database will delete any existing data, but as this issue will only arise on a new deployment on a clean database anyway, that shouldn't be an issue.)

Flask sqlArchemy, html: ValueError: not enough values to unpack (expected 2, got 1)

I am executing the command flask migrate to create the referring tables more at the moment it starts to run, even though it identifies the tables, it throws the following error. I usually look for and find errors easily, but on this occasion I cannot identify it easily.
PDT: I am new to the subject of programming thanks for the understanding and time.
Mainly what I need is to know where the error is to be able to correct it but the extensions that it calls here do not refer to anything that I have written., Thanks
INFO [alembic.autogenerate.compare] Detected added column 'blog_user.youtube'
Traceback (most recent call last):
File "c:\users\user\appdata\local\programs\python\python38-32\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\user\appdata\local\programs\python\python38-32\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\user\Desktop\LLAC\env\Scripts\flask.exe\__main__.py", line 7, in <module>
File "c:\users\user\desktop\llac\env\lib\site-packages\flask\cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "c:\users\user\desktop\llac\env\lib\site-packages\flask\cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "c:\users\user\desktop\llac\env\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "c:\users\user\desktop\llac\env\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\user\desktop\llac\env\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\user\desktop\llac\env\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\user\desktop\llac\env\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "c:\users\user\desktop\llac\env\lib\site-packages\click\decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\user\desktop\llac\env\lib\site-packages\flask\cli.py", line 426, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\user\desktop\llac\env\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "c:\users\user\desktop\llac\env\lib\site-packages\flask_migrate\cli.py", line 89, in migrate
_migrate(directory, message, sql, head, splice, branch_label, version_path,
File "c:\users\user\desktop\llac\env\lib\site-packages\flask_migrate\__init__.py", line 96, in wrapped
f(*args, **kwargs)
File "c:\users\user\desktop\llac\env\lib\site-packages\flask_migrate\__init__.py", line 210, in migrate
command.revision(config, message, autogenerate=True, sql=sql,
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\command.py", line 221, in revision
scripts = [script for script in revision_context.generate_scripts()]
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\command.py", line 221, in <listcomp>
scripts = [script for script in revision_context.generate_scripts()]
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\api.py", line 513, in generate_scripts
yield self._to_script(generated_revision)
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\api.py", line 425, in _to_script
render._render_python_into_templatevars(
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 49, in _render_python_into_templatevars
_render_cmd_body(upgrade_ops, autogen_context)
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 71, in _render_cmd_body
lines = render_op(autogen_context, op)
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 87, in render_op
lines = util.to_list(renderer(autogen_context, op))
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 179, in _add_table
for rcons in [
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 180, in <listcomp>
_render_constraint(cons, autogen_context)
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 775, in _render_constraint
return renderer(constraint, autogen_context)
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 871, in _render_foreign_key
"refcols": ", ".join(
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 872, in <genexpr>
repr(_fk_colspec(f, apply_metadata_schema))
File "c:\users\user\desktop\llac\env\lib\site-packages\alembic\autogenerate\render.py", line 808, in _fk_colspec
tname, colname = tokens[-2:]
ValueError: not enough values to unpack (expected 2, got 1)
I am running into the same error. In my case the error disappears if I remove the table_args . Then the migration works so I think it has probably to do with the ForeignKey constraints.
class AccommodationAirport(db.Model):
__tablename__ = 'accommodation_airport'
__table_args__ = (
ForeignKeyConstraint(
['supplier'], ['accommodation'],
name='fk_acco_airp_sup_acco'
),
UniqueConstraint(
'supplier', 'accommodation', 'airport',
name='uq_sup_acco_airp'
)
)
created = db.Column(db.DateTime, server_default=func.now())
last_modified = db.Column(db.DateTime, onupdate=func.now())
modified_by = db.Column(db.Integer)
supplier = db.Column(db.String(8), primary_key=True)
accommodation = db.Column(db.String(32), primary_key=True)
airport = db.Column(db.String(3), primary_key=True)
The only solution I have found so far is to
comment out the table_args with the Constraint declarations,
migrate -> upgrade
uncomment the table_args
migrate -> upgrade

Using filepaths as global variables in Python

I have a file global_vars.py that contains file paths saved as variables:
from pandas import Timestamp
final_vol_path = 'datasets/final_vols.csv'
final_price_path = 'datasets/final_prices.csv'
final_start_date = Timestamp('2017-01-01')
with other variables written in a similar fashion. However, the functions that I'm using to read in the data throw a FileNotFoundError when attempting to do the following in file1.py:
import scripts.global_vars as gv
read_data(gv.final_vol_path, gv.final_price_path) # throws FileNotFoundError
read_data('datasets/final_vols.csv', 'datasets/final_prices.csv') # this passes
Additionally, I've checked the file paths, and have gotten the following:
gv.final_vol_path == 'datasets/final_vols.csv' # returns True
gv.final_price_path == 'datasets/final_prices.csv' # returns True
Moreover, the pandas Timestamp object is processed without any problems.
Is there any explanation for why the FileNotFoundError is being thrown when attempting to access the file path as a variable from global_vars.py, but is not thrown when the actual string is passed in?
EDIT: The overall directory structure is as follows:
working_dir
L file1.py
L scripts
L global_vars.py
L datasets
L final_vols.csv
L final_prices.csv
EDIT 2: I added in a try-catch block to ensure the rest of the function doesn't break, not sure if that has affected the traceback, but here's what I get:
Traceback (most recent call last):
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\runpy.py", line
184, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\Ananth\Anaconda3\envs\analytics-cpu\Scripts\nose2.exe\__main__.py", line 9, in <module>
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\main.py", line 306, in discover
return main(*args, **kwargs)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\main.py", line 100, in __init__
super(PluggableTestProgram, self).__init__(**kw)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\unittest\main.py", line 93, in __init__
self.parseArgs(argv)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\main.py", line 133, in parseArgs
self.createTests()
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\main.py", line 258, in createTests
self.testNames, self.module)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\loader.py", line 69, in loadTestsFromNames
for name in event.names]
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\loader.py", line 69, in <listcomp>
for name in event.names]
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\loader.py", line 84, in loadTestsFromName
result = self.session.hooks.loadTestsFromName(event)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\events.py", line 224, in __call__
result = getattr(plugin, self.method)(event)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\plugins\loader\testcases.py", line 56, in loadTestsFromName
result = util.test_from_name(name, module)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\util.py", line 106, in test_from_name
parent, obj = object_from_name(name, module)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\nose2\util.py", line 117, in object_from_name
module = __import__('.'.join(parts_copy))
File "C:\Users\Ananth\Desktop\Modules\PortfolioVARModule\tests\test_simulation.py", line 24, in <module>
gv.test_start_date)
File "C:\Users\Ananth\Desktop\Modules\PortfolioVARModule\scripts\prep_data.py", line 119, in read_data
priceDF = pd.read_csv(pricepath).dropna()
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\pandas\io\parsers.py", line 646, in parser_f
return _read(filepath_or_buffer, kwds)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\pandas\io\parsers.py", line 389, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\pandas\io\parsers.py", line 730, in __init__
self._make_engine(self.engine)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\pandas\io\parsers.py", line 923, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "c:\users\ananth\anaconda3\envs\analytics-cpu\lib\site-packages\pandas\io\parsers.py", line 1390, in __init__
self._reader = _parser.TextReader(src, **kwds)
File "pandas\parser.pyx", line 373, in pandas.parser.TextReader.__cinit__ (pandas\parser.c:4184)
File "pandas\parser.pyx", line 667, in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:8449)
FileNotFoundError: File b'datasets/corn_price.csv' does not exist
Problem is the addition of the letter b in front of your file's path.
You get the b because you encoded to utf-8.
Try:
read_data(str(gv.final_vol_path,'utf-8'), str(gv.final_price_path, 'utf-8'))

I faced to django.core.exceptions.ValidationError: ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

data model is below:
class User(models.Model):
user_name = models.CharField(max_length=50)
location = models.CharField(max_length=5)
password = models.CharField(max_length=256,default='')
last_time = models.DateTimeField(null=True,default='')
def __str__(self):
return self.user_name
I just tried python manage.py migrate.
But, Django tells are...(I don't know what I make mistake.)
Operations to perform:
Synchronize unmigrated apps: messages, staticfiles
Apply all migrations: sessions, data, admin, books, auth, poll, contenttypes
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying data.0003_user_last_time...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 147, in apply_migration
state = migration.apply(state, schema_editor)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 179, in add_field
self._remake_table(model, create_fields=[field])
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 77, in _remake_table
self.effective_default(field)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1482, in get_db_prep_value
value = self.get_prep_value(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1461, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1317, in get_prep_value
return self.to_python(value)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1444, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
By now you've probably already found out, but models.DateTimeField doesn't allow for empty strings. Instead, leave out the default attribute. Django will then set the default of the field to None. In addition, set the blank attribute to True as well, so that the field is not required.
last_time = models.DateTimeField(null=True, blank=True)
See Django Documentation on DateTimeField.

Resources