Keywords Must Be Strings When Passing Variable As Parameter - python

I'm trying to pass a variable as a keyword argument like this:
#receiver(post_save, sender=BudgetTransaction)
def create_forecasted(sender, instance, created, **kwargs):
if instance.transaction_type == "EC":
return True
if created:
today = instance.next_date
last_day = date(today.year, 12, 31)
this_month = today.month
weeks_left = int((last_day - today).days / 7)
fortnights_left = int(weeks_left / 2)
months_left = 12 - this_month
if instance.frequency == 'weeks':
create_range = weeks_left
elif instance.frequency == 'fort':
create_range = fortnights_left
else:
create_range = months_left
loop = 1
for i in range(create_range):
if instance.frequency == 'fort':
true_frequency = 'weeks'
true_loop = loop * 2
elif instance.frequency == '4week':
true_frequency = 'weeks'
true_loop = loop * 4
else:
true_frequency = instance.frequency
true_loop = loop
### PASSING VARIABLE HERE ###
next_month = today + relativedelta(**{true_frequency: true_loop})
date_string = next_month.strftime("%Y-%m-%d")
BudgetTransaction.objects.bulk_create([BudgetTransaction(
owner=instance.owner,
transaction_amount=instance.transaction_amount,
transaction_name=instance.transaction_name,
transaction_type=instance.transaction_type,
next_date=date_string,
frequency=instance.frequency,
)])
loop += 1
This is for a django site and it doesn't error when I run this through the site. However, when I run a test I'm getting this error:
Error
Traceback (most recent call last):
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\bf_app\tests\test_models.py", line 26, in test_transaction_has_owner
transaction = TransactionFactory(owner=user)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 40, in __call__
return cls.create(**kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 528, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\django.py", line 117, in _generate
return super()._generate(strategy, params)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 465, in _generate
return step.build()
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\builder.py", line 262, in build
instance = self.factory_meta.instantiate(
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 317, in instantiate
return self.factory._create(model, *args, **kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\django.py", line 166, in _create
return manager.create(*args, **kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\base.py", line 872, in save_base
post_save.send(
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\dispatch\dispatcher.py", line 176, in send
return [
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\dispatch\dispatcher.py", line 177, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\bf_app\models.py", line 82, in create_forecasted
next_month = next_date + relativedelta(**{true_frequency: true_loop})
TypeError: keywords must be strings
I'm not entirely sure how to solve this as I've never passed a keyword as a variable before so I'm not overly familiar with the process. This is happening on a receiver object.
Thanks

The issue here was that occasionally I was passing None as the variable which was returning the error. In the test I added in a proper string parameter and all was fine!

Related

from_personal_row() takes 1 positional argument but 2 were given

The code below (and linked in full here) is attempting to read from a .csv uploaded to Google Sheets, however I cannot get past the following error:
Traceback (most recent call last):
File "import_report.py", line 211, in <module>
main()
File "import_report.py", line 163, in main
all_trackings.extend(objects_to_sheet.download_from_sheet(from_personal_row, sheet_id, tab_name))
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 329, in wrapped_f
return self.call(f, *args, **kw)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 409, in call
do = self.iter(retry_state=retry_state)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 368, in iter
raise retry_exc.reraise()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 186, in reraise
raise self.last_attempt.result()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\_base.py", line 432, in result
return self.__get_result()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\_base.py", line 388, in __get_result
raise self._exception
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 412, in call
result = fn(*args, **kwargs)
File "C:\Users\xxx\Documents\GitHub\order-tracking\lib\objects_to_sheet.py", line 26, in download_from_sheet
return [from_row_fn(header, value) for value in values]
File "C:\Users\xxx\Documents\GitHub\order-tracking\lib\objects_to_sheet.py", line 26, in <listcomp>
return [from_row_fn(header, value) for value in values]
TypeError: from_personal_row() takes 1 positional argument but 2 were given
I've read a lot of threads regarding similar errors other posters have encountered, but I can't figure out how to apply the advice here.
Google Sheet CSV:
Code:
def from_personal_row(row: Dict[str, str]) -> Optional[Tracking]:
tracking_col = row['Carrier Name & Tracking Number']
if not tracking_col:
return None
tracking = tracking_col.split('(')[1].replace(')', '')
orders = {row['Order ID'].upper()}
price_str = str(row['Subtotal']).replace(',', '').replace('$', '').replace('N/A', '0.0')
price = float(price_str) if price_str else 0.0
to_email = row['Ordering Customer Email']
ship_date = get_ship_date(str(row["Shipment Date"]))
street_1 = row['Shipping Address Street 1']
city = row['Shipping Address City']
state = row['Shipping Address State']
address = f"{street_1} {city}, {state}"
group, reconcile = get_group(address)
if group is None:
return None
tracked_cost = 0.0
items = price_str
merchant = 'Amazon'
return Tracking(
tracking,
group,
orders,
price,
to_email,
ship_date=ship_date,
tracked_cost=tracked_cost,
items=items,
merchant=merchant,
reconcile=reconcile)

ImageDataBunch not loading in my files/labels

I have a dataset of images stored on my local disk that I name as such:
path = '../input/resized/Resized Dataset.zip/Resized Data'
And I am calling an instance of an ImageDataBunch from the fastai.vision library using the following code:
data = ImageDataBunch.from_folder(path, train=".", ds_tfms=get_transforms(),size=224, valid_pct=0.2)
but for some reason I am getting an error
File "../src/script.py", line 17, in <module>
data = ImageDataBunch.from_folder(path, train=".", ds_tfms=get_transforms(),size=20, valid_pct=0.2)
File "/opt/conda/lib/python3.6/site-packages/fastai/vision/data.py", line 110, in from_folder
src = src.label_from_folder(classes=classes)
File "/opt/conda/lib/python3.6/site-packages/fastai/data_block.py", line 463, in _inner
self.train = ft(*args, from_item_lists=True, **kwargs)
File "/opt/conda/lib/python3.6/site-packages/fastai/data_block.py", line 292, in label_from_folder
label_cls=label_cls, **kwargs)
File "/opt/conda/lib/python3.6/site-packages/fastai/data_block.py", line 287, in label_from_func
return self._label_from_list([func(o) for o in self.items], label_cls=label_cls, **kwargs)
File "/opt/conda/lib/python3.6/site-packages/fastai/data_block.py", line 262, in _label_from_list
label_cls = self.get_label_cls(labels, label_cls=label_cls, **kwargs)
File "/opt/conda/lib/python3.6/site-packages/fastai/data_block.py", line 251, in get_label_cls
it = index_row(labels,0)
File "/opt/conda/lib/python3.6/site-packages/fastai/core.py", line 250, in index_row
3.5s
3
return a[idxs]
IndexError: index 0 is out of bounds for axis 0 with size 0
I have used multiple different datasets and have the same problem

Django - F('datetimefield') + relativedelta(months=1) fails

I am trying to update a self datetime field of a model using F() object in django.
HeatWatchList.objects.filter(
user=request.user,
next_date_to__lt=datetime.combine(datetime.now().date(), time.min)
).update(
next_date_from = F('next_date_from') + relativedelta(months=1),
next_date_to = F('next_date_to') + relativedelta(months=1)
)
But when doing this i got AttributeError: relativedelta object has no attribute translate.
Here is the traceback i got when executing the code maybe it has an issue using the F() object when adding value with a datetime type relativedelta.
Traceback (most recent call last):
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\farm_management\heat\views.py", line 192, in update_watchlist
next_date_to = F('next_date_to') + relativedelta(months=1)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\query.py", line 637, in update
rows = query.get_compiler(self.db).execute_sql(CURSOR)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\sql\compiler.py", line 1148, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\backends\mysql\base.py", line 110, in execute
return self.cursor.execute(query, args)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\cursors.py", line 164, in execute
query = self.mogrify(query, args)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\cursors.py", line 143, in mogrify
query = query % self._escape_args(args, conn)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\cursors.py", line 118, in _escape_args
return tuple(conn.literal(arg) for arg in args)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\cursors.py", line 118, in <genexpr>
return tuple(conn.literal(arg) for arg in args)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\connections.py", line 800, in literal
return self.escape(obj, self.encoders)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\connections.py", line 793, in escape
return escape_item(obj, self.charset, mapping=mapping)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\converters.py", line 27, in escape_item
val = encoder(val, mapping)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\converters.py", line 110, in escape_unicode
return u"'%s'" % _escape_unicode(value)
File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\pymysql\converters.py", line 73, in _escape_unicode
return value.translate(_escape_table)
AttributeError: 'relativedelta' object has no attribute 'translate'
Seems like pymysql's converters does not support relativedelta objects.
One possible solution is to iterate over objects and update it (inefficient):
objects_list = HeatWatchList.objects.filter(
user=request.user,
next_date_to__lt=datetime.combine(datetime.now().date(), time.min)
)
for obj in object_list:
obj.next_date_from = onj.next_date_from + relativedelta(months=1)
obj.next_date_to = onj.next_date_to + relativedelta(months=1)
objsave()
Or better use datetime.timedelta instead of relativedelta if it possible:
HeatWatchList.objects.filter(
user=request.user,
next_date_to__lt=datetime.combine(datetime.now().date(), time.min)
).update(
next_date_from = F('next_date_from') + timedelta(days=31),
next_date_to = F('next_date_to') + timedelta(days=31)
)

ProgrammingError: can't adapt type 'stock.location' - Odoo v9

I'm migrating an Odoo v8 module, which is used to upload .csv's into stock.inventory model.
I've fixed a few things, but I still have some bugs on it, like this method:
#api.one
def action_import(self):
"""Load Inventory data from the CSV file."""
ctx = self._context
stloc_obj = self.env['stock.location']
inventory_obj = self.env['stock.inventory']
inv_imporline_obj = self.env['stock.inventory.import.line']
product_obj = self.env['product.product']
if 'active_id' in ctx:
inventory = inventory_obj.browse(ctx['active_id'])
if not self.data:
raise exceptions.Warning(_("You need to select a file!"))
# Decode the file data
data = base64.b64decode(self.data)
file_input = cStringIO.StringIO(data)
file_input.seek(0)
location = self.location
reader_info = []
if self.delimeter:
delimeter = str(self.delimeter)
else:
delimeter = ','
reader = csv.reader(file_input, delimiter=delimeter,
lineterminator='\r\n')
try:
reader_info.extend(reader)
except Exception:
raise exceptions.Warning(_("Not a valid file!"))
keys = reader_info[0]
# check if keys exist
if not isinstance(keys, list) or ('code' not in keys or
'quantity' not in keys):
raise exceptions.Warning(
_("Not 'code' or 'quantity' keys found"))
del reader_info[0]
values = {}
actual_date = fields.Date.today()
inv_name = self.name + ' - ' + actual_date
inventory.write({'name': inv_name,
'date': fields.Datetime.now(),
'imported': True, 'state': 'confirm'})
for i in range(len(reader_info)):
val = {}
field = reader_info[i]
values = dict(zip(keys, field))
prod_location = location.id
if 'location' in values and values['location']:
locat_lst = stloc_obj.search([('name', '=',
values['location'])])
if locat_lst:
prod_location = locat_lst[0]
prod_lst = product_obj.search([('default_code', '=',
values['code'])])
if prod_lst:
val['product'] = prod_lst[0].id
if 'lot' in values and values['lot']:
val['lot'] = values['lot']
val['code'] = values['code']
val['quantity'] = values['quantity']
val['location_id'] = prod_location
val['inventory_id'] = inventory.id
val['fail'] = True
val['fail_reason'] = _('No processed')
inv_imporline_obj.create(val)
Everytime, I click on the button which calls for this function, to upload the csv file it throws me this:
2016-11-02 23:18:38,659 16865 ERROR moto_backup openerp.http: Exception during JSON request handling.
Traceback (most recent call last):
File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 648, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 685, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 321, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 314, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 964, in call
return self.method(*args, **kw)
File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 514, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov9/odoo-9.0/addons/web/controllers/main.py", line 892, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov9/odoo-9.0/addons/web/controllers/main.py", line 880, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/api.py", line 421, in old_api
result = new_api(recs, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/api.py", line 425, in new_api
result = [method(rec, *args, **kwargs) for rec in self]
File "/home/kristian/odoov9/motostion_addons/odoomrp-wip-9.0/stock_inventory_import/wizard/import_inventory.py", line 89, in action_import
inv_imporline_obj.create(val)
File "/home/kristian/odoov9/odoo-9.0/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/models.py", line 4157, in create
record = self.browse(self._create(old_vals))
File "/home/kristian/odoov9/odoo-9.0/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/api.py", line 490, in new_api
result = method(self._model, cr, uid, *args, **old_kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/models.py", line 4301, in _create
tuple([u[2] for u in updates if len(u) > 2])
File "/home/kristian/odoov9/odoo-9.0/openerp/sql_db.py", line 141, in wrapper
return f(self, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0/openerp/sql_db.py", line 220, in execute
res = self._obj.execute(query, params)
ProgrammingError: can't adapt type 'stock.location'
I guess the is something with the new api that I'm missing,
Please, any ideas about this?
A little mistake, you're trying to pass the stock.location object you got directly from your search query instead of the id
Change this line
if locat_lst:
prod_location = locat_lst[0]
to
if locat_lst:
prod_location = locat_lst[0].id

ValidationError in Django Model

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

Categories

Resources