It's the first time I'm trying 'PolymorphicModel', maybe there is something I'm doing wrong or I'm trying to do something that is not supported. Is there anyway to get around this?
My simplified model:
from django.polymorphic import PolymorphicModel
class Question(PolymorphicModel):
description = models.TextField(default='')
compound_question = models.ForeignKey('CompoundQuestion',
on_delete=models.CASCADE,
blank=True,
null=True,
related_name='sub_questions')
bonus_question = models.OneToOneField('BonusQuestion',
on_delete=models.CASCADE,
blank=True,
null=True,
related_name='question')
class SimpleQuestion(Question):
pass
class CompoundQuestion(Question):
pass
class BonusQuestion(Question):
pass
If I create the necessary instances,
compound_q = CompoundQuestion()
compound_q.save()
simple_q2 = SimpleQuestion(compound_question=compound_q)
simple_q2.save()
bonus_q = BonusQuestion(compound_question=compound_q)
bonus_q.save()
simple_q1 = SimpleQuestion(bonus_question=bonus_q)
simple_q1.save()
so that in the end I end up with:
compound_q.sub_questions.all()
>>> <PolymorphicQuerySet [<BonusQuestion: BonusQuestion object (5)>, <SimpleQuestion: SimpleQuestion object (8)>]>
After I do compound_q.delete()
I get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/base.py", line 936, in delete
collector.collect([self], keep_parents=keep_parents)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 245, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 17, in CASCADE
source_attr=field.name, nullable=field.null)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 226, in collect
sub_objs = self.related_objects(related, batch)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 257, in related_objects
**{"%s__in" % related.field.name: objs}
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File ".../Python/Django/env/lib/python3.6/site-packages/polymorphic/query.py", line 173, in _filter_or_exclude
negate, *(list(q_objects) + additional_args), **kwargs
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1340, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1371, in _add_q
check_filterable=check_filterable,
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1274, in build_filter
self.check_related_objects(join_info.final_field, value, join_info.opts)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1115, in check_related_objects
self.check_query_object_type(v, opts, field)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1095, in check_query_object_type
(value, opts.object_name))
ValueError: Cannot query "SimpleQuestion object (8)": Must be "BonusQuestion" instance.
Is there something wrong with my model? Everything else seems to be working as expected.
Thanks for reading :)
This appears to be a known bug in the django-polymorphic package. There is a work around suggested here to add a vanilla Manager to your class and to set this manager as the default
class Question(PolymorphicModel):
non_polymorphic = models.Manager()
class Meta
base_manager_name = 'non_polymorphic'
Related
I am using Django-import-export for importing data but facing an error given below.
i am using django 4.0.6 python 3.10.5 with PostgreSql and most latest version of django import export
Code settings i tried to import data to postgresql database by django-import-export
class MemberResource(resources.ModelResource):
Brand=Field()
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
def dehydrate_Brand(self, obj):
return str(obj.Brand.title)
class modelAdmin(ImportExportModelAdmin):
resource_class = MemberResource
list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories']
search_fields = ['title','Model_code','Chipset',]
fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat')
admin.site.register(model,modelAdmin)
and got below error also attached the image where i exported the data from app and then edited the same and tried to import and stuck with below error.
[Line number: 1 - Field 'id' expected a number but got ''.
2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in _get_
rel_obj = self.field.get_cached_value(instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
return instance._state.fields_cache\[cache_name\]
KeyError: 'Brand'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1988, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row
diff = self.get_diff_class()(self, original, new)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in _init_
self.left = self._export_resource_fields(resource, instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields
return \[resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()\]
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in <listcomp>
return \[resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()\]
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 919, in export_field
return method(obj)
File "C:\Users\gsminfinity\Desktop\Master\admin\firmApp\admin.py", line 20, in dehydrate_Brand
return str(obj.Brand.title)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 205, in _get_
rel_obj = self.get_object(instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 168, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 482, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in build_filter
return self._add_q(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1448, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\lookups.py", line 27, in _init_
self.rhs = self.get_prep_lookup()
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\lookups.py", line 85, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1990, in get_prep_value
raise e._class_(
ValueError: Field 'id' expected a number but got ''.][1]
the issue was dehydrating foreign key gives only read-only data which was for the purpose of export only to import we need to use the widgets which will resolve the foreign keys and import the data to database.
Link to Documentation
class MemberResource(resources.ModelResource):
Brand = fields.Field(
column_name='Brand',
attribute='Brand',
widget=ForeignKeyWidget(brand, 'title'))
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
That means that there are missing values in the "id" column.
I don't know "Django import / export", sounds very good. An old way of mine with any import/export is to export some sample data and then open it in excel or pandas. Because of the following:
You have all the required columns.
The columns are in the correct order.
And if you have test data you can see the data-types of each column.
Take care using Excel because it changes True into TRUE and generates weird date formats.
Another issue is that after importing django u must also be aware of the last "id" number in order to give the correct AutoIncrement for a new record. That's usually corrected with SQL, but maybe "Django-import-export" corrects this automatically.
I need a similar code to this SQL:
SELECT * FROM tab WHERE a = CASE WHEN x IS NULL THEN b ELSE c END
my attempt, but to no success:
model.objects.filter(a=Q(Case(When(x__isnull=True, then='b'), default='c')))
when I try to run, I get this error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1340, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q
check_filterable=check_filterable,
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1249, in build_filter
value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1058, in resolve_lookup_value
value = value.resolve_expression(self, **kwargs)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query_utils.py", line 95, in resolve_expression
check_filterable=False,
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q
check_filterable=check_filterable,
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1237, in build_filter
arg, value = filter_expr
TypeError: cannot unpack non-iterable Case object
You should not wrap this in a Q object, since a Q object is a condition, a Case is not something that can be True or False:
from django.db.models import Case, When
model.objects.filter(a=Case(When(x__isnull=True, then='b'), default='c'))
Note that you can replace x__isnull=True with simply x=None, which is slightly shorter:
from django.db.models import Case, When
model.objects.filter(a=Case(When(x=None, then='b'), default='c'))
I have one innormal idea to get object through function and set to it certain field for filtering
It will look as follows
get_course(name='math')
# or
get_course(id=12)
# and so on
def get_course(**kwargs):
for key, val in kwargs:
return Course.objects.get(key=val)
I've tried:
key = 'id'
val = 1
Course.objects.filter(key=val)
And result was:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1190, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1049, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1420, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'key' into field. Choices are: complexity, course, created, description, id, image, image_courses_and_course, image_dash, is_active, is_certificated, is_video, modules, name, question, queue_number, quiz, selected_courses, short_description, tagged_items, tags, total_ended, total_started, total_watches, updated, users_ended, users_likes, users_started, video_link
So is it possible to make this stuff?
To pass variable keyword parameters to functions in python you can use dictionary unpacking
This
foo(**{'bar': 'baz'})
Is equivalent to
foo(bar='baz')
You could probably do something like this
def get_course(**kwargs):
return Course.objects.get(**kwargs)
Have you tried running this code and if so, what's the issue you're running into? This looks fine to me.
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])
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