I defined the Test model as:
class Test(models.Model):
name = models.BinaryField(blank=False)
time = models.TimeField()
# one test case has many tests
testcase = models.ForeignKey(TestCase)
def __str__(self):
return self.name
when I try to parse a xml file to create the model object I have the following method:
def add_test(testcase, obj):
kwargs = {
'name': "",
'time': None,
}
status = 1
# create the test object
for k, v in obj.iteritems():
if k == '#name':
kwargs['name'] = v if v is not None else ""
elif k == '#time':
kwargs['time'] = v
print kwargs
test = Test(testcase=testcase, **kwargs)
test.save()
There, testcase is the oject of the TestCase model. The kwargs have the correct input:
{'name': u'runTest', 'time': u'36.332'}
However, when I invoke the above function I get:
Traceback (most recent call last):
File "dbsync.py", line 131, in <module>
add_testsuite("scale")
File "dbsync.py", line 55, in add_testsuite
add_testcases(testsuite, testcases)
File "dbsync.py", line 87, in add_testcases
status = add_test(testcase_obj, testcase)
File "dbsync.py", line 103, in add_test
test.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 710, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 738, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 822, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 861, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 920, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 970, in execute_sql
for sql, params in self.as_sql():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 928, in as_sql
for obj in self.query.objs
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2293, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2288, in get_prep_value
return self.to_python(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2275, in to_python
params={'value': value},
django.core.exceptions.ValidationError
I don't quite get what's going on there ... any clues?
To make this work you have to convert your string into a datetime.time.
kwargs['time'] = datetime.datetime.strptime(v, 'YOUR_TIME_FORMAT').time()
Replace YOUR_TIME_FORMAT with the input time format you have.
It's not complaining about the way you pass in your variables, it's raising a ValidationError and I have a funny feeling that it's missing the last line of the traceback, which would tell us what is wrong with your values.
I didn't test the BinaryField, but the TimeField is complaining about your value. I haven't tested the BinaryField, but just looking at the TimeField, shows the following:
File "<console>", line 1, in <module>
File "/home/paco/Projects/sandeepbox/stackoverflow/bla/bla/field_validation.py", line 16, in <module>
print a.is_valid()
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 184, in is_valid
return self.is_bound and not self.errors
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 176, in errors
self.full_clean()
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 392, in full_clean
self._clean_fields()
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 407, in _clean_fields
value = field.clean(value)
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/fields.py", line 162, in clean
value = self.to_python(value)
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/fields.py", line 474, in to_python
return super(TimeField, self).to_python(value)
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/fields.py", line 423, in to_python
for format in self.input_formats:
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/functional.py", line 136, in __wrapper__
res = func(*self.__args, **self.__kw)
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/formats.py", line 110, in get_format
for module in get_format_modules(lang):
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/formats.py", line 82, in get_format_modules
modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)))
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/formats.py", line 51, in iter_format_modules
if not check_for_language(lang):
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 181, in check_for_language
return _trans.check_for_language(lang_code)
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 125, in wrapper
result = user_function(*args, **kwds)
File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 409, in check_for_language
if not language_code_re.search(lang_code):
TypeError: expected string or buffer
with the following code (no need for models to show the validation):
from django import forms
class Test(forms.Form):
time = forms.TimeField()
def __str__(self):
return self.name
kwargs = {'time': u'36.332'}
a = Test(kwargs)
print a.is_valid()
You need to pass in your data this way:
import datetime
from django import forms
class Test(forms.Form):
time = forms.TimeField()
def __str__(self):
return self.name
kwargs = {'time': datetime.datetime.now().time()}
a = Test(kwargs)
print a.is_valid()
The code, this time, actually prints True
Related
when i try to close my session and post entries for my POS,
I had this error :
Odoo Server Error
Traceback (most recent call last):
File "/opt/odoo14/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "/opt/odoo14/odoo/http.py", line 683, in dispatch
result = self._call_function(**self.params)
File "/opt/odoo14/odoo/http.py", line 359, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/odoo14/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/odoo14/odoo/http.py", line 347, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/odoo14/odoo/http.py", line 912, in call
return self.method(*args, **kw)
File "/opt/odoo14/odoo/http.py", line 531, in response_wrap
response = f(*args, **kw)
File "/opt/odoo14/addons/web/controllers/main.py", line 1393, in call_button
action = self._call_kw(model, method, args, kwargs)
File "/opt/odoo14/addons/web/controllers/main.py", line 1381, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/opt/odoo14/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/opt/odoo14/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/opt/odoo14/custom_addons/bi_pos_pay_later/models/pos_session.py", line 35, in action_pos_session_closing_control
session.action_pos_session_close()
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 295, in action_pos_session_close
return self._validate_session()
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 311, in _validate_session
self.with_company(self.company_id)._create_account_move()
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 408, in _create_account_move
data = self._create_invoice_receivable_lines(data)
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 657, in _create_invoice_receivable_lines
receivable_line = MoveLine.create(vals)
File "", line 2, in create
File "/opt/odoo14/odoo/api.py", line 345, in _model_create_multi
return create(self, arg)
File "/opt/odoo14/addons/account/models/account_move.py", line 3843, in create
lines = super(AccountMoveLine, self).create(vals_list)
File "", line 2, in create
File "/opt/odoo14/odoo/api.py", line 345, in _model_create_multi
return create(self, arg)
File "/opt/odoo14/odoo/addons/base/models/ir_fields.py", line 533, in create
recs = super().create(vals_list)
File "", line 2, in create
File "/opt/odoo14/odoo/api.py", line 345, in _model_create_multi
return create(self, arg)
File "/opt/odoo14/odoo/models.py", line 3868, in create
records = self._create(data_list)
File "/opt/odoo14/odoo/models.py", line 3974, in _create
cr.execute(query, params)
File "", line 2, in execute
File "/opt/odoo14/odoo/sql_db.py", line 101, in check
return f(self, *args, **kwargs)
File "/opt/odoo14/odoo/sql_db.py", line 298, in execute
res = self._obj.execute(query, params)
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/odoo14/odoo/http.py", line 639, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/odoo14/odoo/http.py", line 315, in _handle_exception
raise exception.with_traceback(None) from new_cause
psycopg2.ProgrammingError: can't adapt type 'res.partner'
this happened especially if some of my POS orders are invoiced ( defined with customers ) How can i solve it ?
i use odoo 14 enterprise hosted on premise.
The shared error log says you use third-party modules like 'bi_pos_pay_later'. Kindly make sure that these modules are not the ones causing errors by creating a new database with these modules and checking the same workflow. If you find that the issue is with the third-party modules, kindly report the same to its developers since they will be better suited to help you.
I have exported csv files from the database and would like to store the csv information in my django models. I am receiving the ValueError problem.
I have tried converting the string to an integer within my .py files
load_vendor_data.py
import csv
from polls.models import Vendors
with open('../data/csv/Vendors.csv') as cap:
reader = csv.reader(cap)
# i = 0
for row in reader:
vendors = Vendors(row[0],row[1],row[2])
vendors.save()
# i = i + 1
models.py
class Vendors(models.Model):
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
price_range = models.CharField(max_length=100)
def __str__(self):
return self.name
class Act(models.Model):
Name = models.CharField(max_length=100)
Stage = models.CharField(max_length=100)
Start_Time = models.TimeField()
End_Time = models.TimeField()
Date = models.DateField()
def __str__(self):
return self.name
Stacktrace
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\tawhi\project\2019-ca472-John-Tawhid\festimaps\polls\load_vendor_data.py", line 9, in <module>
vendors.save()
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 807, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 837, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 904, in _save_table
forced_update)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 934, in _do_update
filtered = base_qs.filter(pk=pk_val)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\query.py", line 784, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\sql\query.py", line 1250, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\sql\query.py", line 1276, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\sql\query.py", line 1210, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\sql\query.py", line 1104, in build_lookup
return final_lookup(lhs, rhs)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\lookups.py", line 74, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'Umi Falafel'
I expect no errors when importing the csv files inside the django db
You should always use keyword arguments, not positional ones, when instantiating models.
vendors = Vendors(name=row[0], location=row[1], price_range=row[2])
EDIT: I've changed the title to better represent the solution I seeking.
I'm repeating a block of code and would like to a write a function to reduce clutter. I'm having trouble passing in the kwarg key hourly_id (last line of the original code).
Original Code
# Create Hourly data.
hourly_data = validated_data.pop('hourly')
hourly_points_data = hourly_data.pop('data')
hourly = Hourly.objects.create(**hourly_data)
for hourly_point_data in hourly_points_data:
hourly_point = HourlyPoint.objects.create(
hourly_id=hourly.pk, **hourly_point_data) <-- This
New Function
def create_data_block(self, data, block_str, DataBlock, DataPoint, id):
block_data = data.pop(block_str)
points_data = block_data.pop('data')
block = DataBlock.objects.create(**block_data)
for point_data in points_data:
point = DataPoint.objects.create(
id=block.pk, **point_data) <-- This
Function Call
self.create_data_block(validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id')
So you can see here I am trying to pass hourly_id as id using a string, but I get a database error saying that that hourly_id was missing so I'm clearly not passing it in correctly.
Traceback
Traceback (most recent call last):
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.5/contextlib.py", line 30, in inner
return func(*args, **kwds)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/home/cudb/Projects/a/b/c/weather/views.py", line 36, in get
response = self.get_entry(latitude, longitude)
File "/home/cudb/Projects/a/b/c/weather/views.py", line 59, in get_entry
response = self.create_or_update_entry(latitude, longitude)
File "/home/cudb/Projects/a/b/c/weather/views.py", line 76, in create_or_update_entry
location_serializer.save()
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save
self.instance = self.create(validated_data)
File "/home/cudb/Projects/a/b/c/weather/serializers.py", line 119, in create
validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id')
File "/home/cudb/Projects/a/b/c/weather/serializers.py", line 169, in create_data_block
id=block.pk, **point_data)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/query.py", line 399, in create
obj.save(force_insert=True, using=self.db)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 947, in _do_insert
using=using, raw=raw)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/query.py", line 1045, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 164, in execute
return self._record(self.cursor.execute, sql, params)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 106, in _record
return method(sql, params)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "hourly_id" violates not-null constraint
DETAIL: Failing row contains (6, 76.22, 77.31, 0.80, 0.00, clear-night, Clear, null).
[04/Aug/2017 12:05:30] "GET /weather/0,4 HTTP/1.1" 500 288106
This where I see a problem:
hourly_point = HourlyPoint.objects.create(hourly_id=hourly.pk, **hourly_point_data)
point = DataPoint.objects.create(id=block.pk, **point_data)
You can rename the variables to be more generic as you see fit, but hourly_id is not a variable, it's a named parameter. By using id instead, you're not passing in the expected hourly_id argument but passing in a potentially unwanted, or incorrect, id argument.
Unless you change the definition of create() itself, the argument name remains hourly_id. One way around this is to use the argument positionally, if possible, instead of by name. (I.e. is it a keyword argument only or a positional argument being accessed by keyword?)
Alternatively, if you pass in 'hourly_id' as id then augment point_data with this key and value:
def create_data_block(self, data, block_str, DataBlock, DataPoint, id):
block_data = data.pop(block_str)
points_data = block_data.pop('data')
block = DataBlock.objects.create(**block_data)
for point_data in points_data:
point = DataPoint.objects.create(**{id: block.pk, **point_data})
I have an enum... defined very similarly to here.
When I try to create a table using the enum, as in the example, I get an error during table creation. It is a very vague error. Here is code that replicates the problem:
from sqlalchemy import Table, MetaData, Column, Enum, create_engine
import enum
class myEnum(enum.Enum):
one = 'one'
two = 'two'
three = 'three'
def main():
e = create_engine('sqlite:///:memory:')
e.echo = True
m = MetaData(bind = e)
t = Table('table', m, Column('my_enum', Enum(myEnum)))
t.create()
if __name__ == '__main__': main()
I get an AttributeError: replace when I run this code, with a seemingly useless stacktrace. I honestly don't even know where to begin debugging this and while I can conceive of a couple of possible workarounds, I am relatively new to SQLAlchemy so I'm not sure what the cleanest solution is. Surely basic enum support is a relatively simple expectation of a ORM framework?
Here is the full stack trace:
Traceback (most recent call last):
File "table_test.py", line 17, in <module>
if __name__ == '__main__': main()
File "table_test.py", line 16, in main
t.create()
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 725, in create
checkfirst=checkfirst)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1856, in _run_visitor
conn._run_visitor(visitorcallable, element, **kwargs)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1481, in _run_visitor
**kwargs).traverse_single(element)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 121, in traverse_single
return meth(obj, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\ddl.py", line 764, in visit_table
include_foreign_key_constraints=include_foreign_key_constraints
File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 914, in execute
return meth(self, multiparams, params)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\ddl.py", line 68, in _execute_on_connection
return connection._execute_ddl(self, multiparams, params)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 962, in _execute_ddl
compiled = ddl.compile(dialect=dialect)
File "<string>", line 1, in <lambda>
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 494, in compile
return self._compiler(dialect, bind=bind, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\ddl.py", line 26, in _compiler
return dialect.ddl_compiler(dialect, self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 190, in __init__
self.string = self.process(self.statement, **compile_kwargs)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 213, in process
return obj._compiler_dispatch(self, **kwargs)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
return meth(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 2173, in visit_create_table
create.include_foreign_key_constraints)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 2220, in create_table_constraints
for constraint in constraints
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 2218, in <genexpr>
p for p in
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 2226, in <genexpr>
not getattr(constraint, 'use_alter', False)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 213, in process
return obj._compiler_dispatch(self, **kwargs)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 93, in _compiler_dispatch
return meth(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 2369, in visit_check_constraint
literal_binds=True)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 213, in process
return obj._compiler_dispatch(self, **kwargs)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
return meth(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 927, in visit_binary
return self._generate_generic_binary(binary, opstring, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 944, in _generate_generic_binary
binary.right._compiler_dispatch(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
return meth(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 527, in visit_grouping
return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
return meth(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 751, in visit_clauselist
for c in clauselist.clauses)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 748, in <genexpr>
s for s in
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 751, in <genexpr>
for c in clauselist.clauses)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
return meth(self, **kw)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1071, in visit_bindparam
bindparam, within_columns_clause=True, **kwargs)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1103, in render_literal_bindparam
return self.render_literal_value(value, bindparam.type)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1118, in render_literal_value
return processor(value)
File "C:\Anaconda3\lib\site-packages\sqlalchemy\sql\sqltypes.py", line 171, in process
value = value.replace("'", "''")
File "C:\Anaconda3\lib\enum.py", line 268, in __getattr__
raise AttributeError(name) from None
AttributeError: replace
PEP-435 enum support is being added in 1.1.
1.1.0b1 was recently released. You can upgrade to 1.1.0b1 but be wary of bugs. Based on release history I would say the stable version should be released in a month or two.
how to upgrade:
pip install 'sqlalchemy==1.1.0b3'
I have deleted all migrations in the project, deleted the database and trying to re-create migrations with manage.py makemigrations command.
But I'm getting the error:
Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 41, in <module>
run_module(manage_file, None, '__main__', True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 176, in run_module
fname, loader, pkg_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 82, in _run_module_code
mod_name, mod_fname, mod_loader, pkg_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/Users/rankor/src/python/web/Auction/Auction/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute
self.check()
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config
return check_resolver(resolver)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver
for pattern in resolver.url_patterns:
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/rankor/src/python/web/Auction/Auction/Auction/urls.py", line 14, in <module>
url(r'^orders/', include('orders.urls', namespace='orders')),
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/rankor/src/python/web/Auction/Auction/orders/urls.py", line 3, in <module>
from orders.views import CreateOrderView, OrdersView, OrderView
File "/Users/rankor/src/python/web/Auction/Auction/orders/views.py", line 7, in <module>
from orders.forms import OrderForm
File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 47, in <module>
class OrderForm(ModelForm):
File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 60, in OrderForm
widget=forms.Select, queryset=OrderCategory.objects.filter(parent__isnull=False).order_by('ordering'))
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/forms/models.py", line 1142, in __init__
self.queryset = queryset
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/forms/models.py", line 1168, in _set_queryset
self.widget.choices = self.choices
File "/Users/rankor/src/python/web/Auction/Auction/orders/forms.py", line 16, in _get_choices
if not self.queryset:
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 266, in __nonzero__
return type(self).__bool__(self)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 262, in __bool__
self._fetch_all()
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
results = compiler.execute_sql()
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 852, in execute_sql
cursor.execute(sql, params)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/rankor/src/python/web/Auction/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: orders_ordercategory
OrderForm:
class OrderForm(ModelForm):
"""
Order form
"""
class Meta:
model = Order
fields = ('city', 'category', 'title', 'min_price', 'max_price', 'description', 'delivery_type', 'valid_to')
city = forms.ModelChoiceField(
widget=forms.Select, queryset=City.objects.filter(country__code='RU').order_by('name'))
category = CategoryChoiceField(
widget=forms.Select, queryset=OrderCategory.objects.filter(parent__isnull=False).order_by('ordering'))
valid_to = forms.DateField(widget=SelectDateWidget)
class GroupedModelChoiceField(forms.ModelChoiceField):
def optgroup_from_instance(self, obj):
return ""
def __choice_from_instance__(self, obj):
return obj.id, self.label_from_instance(obj)
def _get_choices(self):
if not self.queryset:
return []
all_choices = []
if self.empty_label:
current_optgroup = ""
current_optgroup_choices = [("", self.empty_label)]
else:
current_optgroup = self.optgroup_from_instance(self.queryset[0])
current_optgroup_choices = []
for item in self.queryset:
optgroup_from_instance = self.optgroup_from_instance(item)
if current_optgroup != optgroup_from_instance:
all_choices.append((current_optgroup, current_optgroup_choices))
current_optgroup_choices = []
current_optgroup = optgroup_from_instance
current_optgroup_choices.append(self.__choice_from_instance__(item))
all_choices.append((current_optgroup, current_optgroup_choices))
return all_choices
choices = property(_get_choices, forms.ChoiceField._set_choices)
class CategoryChoiceField(GroupedModelChoiceField):
def optgroup_from_instance(self, obj):
return obj.parent.title
Why and how to fix it?
P.S. Django 1.9, python 2.7, OS X.
Look at the stacktrace.
During the warm up process, Django imports all models and urls.
You should move queryset initialization to the init method of your OrderForm.
For a more general note, and to answer Lorenzo. In all cases you want to move fields querysets initialisation to the init method of your form or moved them to your views. Why? Actually, when Django is started, it can import some of your forms, the form class is built and the same happen with your field-class attributes. As a result, the queryset is fetched directly, once and for all, when importing your form and stays constant as long as you do not reload the server, so if you ever add data to your OrderCategory it will never appear in your select widget.
The "workaround" is to move queryset initialisation to the init method of the form.
In your case :
class OrderForm(ModelForm):
def __init__(self, *args, **kwargs):
super(OrderForm, self).__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.filter(country__code='RU').order_by('name')
self.fields['category'].queryset = OrderCategory.objects.filter(parent__isnull=False).order_by('ordering')
class Meta:
#...
# ... fields definition
See Fields which handle relationships for relative Django documentation.