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.
Related
When I try run python manage.py migrate to synchronize database I get error
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 346, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/Library/Python/2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/Library/Python/2.7/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/Python/2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor)
File "/Library/Python/2.7/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/Python/2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/schema.py", line 179, in add_field
self._remake_table(model, create_fields=[field])
File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/schema.py", line 77, in _remake_table
self.effective_default(field)
File "/Library/Python/2.7/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 702, in get_db_prep_value
value = self.get_prep_value(value)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 1804, in get_prep_value
return float(value)
ValueError: could not convert string to float: Jestem watowcem
models.py file:
# -*- coding: utf-8 -*-
from django.db import models
# Create your models here.
class ProductWithFrames(models.Manager):
def get_queryset(self):
return super(ProductWithFrames, self).get_queryset().filter(has_frame=True)
class ProductWithoutFrames(models.Manager):
def get_queryset(self):
return super(ProductWithoutFrames, self).get_queryset().filter(has_frame=False)
class Product(models.Model):
PRODUCT_SIZE = (
('50x50', '50x50'),
('50x70', '50x70'),
('70x50', '70x50'),
)
product_id = models.IntegerField()
product_size = models.CharField(max_length = 5, choices = PRODUCT_SIZE, default='50x50')
product_price = models.PositiveSmallIntegerField()
has_frame = models.BooleanField(default = False)
products = models.Manager()
products_with_frames = ProductWithFrames()
products_without_frames = ProductWithoutFrames()
def _has_frame(self):
if self.has_frame == True:
return True
return False
# _has_frame.boolean = True
# has_frame = property(_has_frame)
def __str__(self):
if self.has_frame:
return "Oprawiony rozmiar ramy {} kosztuje {} zl".format(self.product_size, self.product_price)
else:
return "Nieoprawiony rozmiar ramy {} kosztuje {} zl".format(self.product_size, self.product_price)
So in my own code I haven't got any String like "Jestem watowcem". I have just removed it for test but error is still visible.
python manage.py makemigration <app> goes correctly
python manage.py migrate - call errors like above
Only one file from Error List is editable and it is manage.py but I haven't edited it since beggining of project.
So if in my own code I haven't got String variable but Python want to tell me that it can't convert value, does anybody know what can I do or where should I remove this variable?
I'm trying to run a test in Django and I keep getting this error when Django tries to create the test DB.
django.db.utils.ProgrammingError: relation "userprofile_user" does not exist
Here is my UserProfile model:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
gender = models.CharField(max_length=140, null=True)
age_range_min = models.PositiveIntegerField(null=True)
age_range_max = models.PositiveIntegerField(null=True)
locale = models.CharField(max_length=255, null=True)
def __unicode__(self):
return u'Profile of user: %s' % self.user.email
Here is the full stack trace:
Destroying old test database 'default'...
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
super(Command, self).execute(*args, **options)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
failures = test_runner.run_tests(test_labels)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests
old_config = self.setup_databases()
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
**kwargs
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
test_flush=not keepdb,
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
return command.execute(*args, **defaults)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 318, in sync_apps
cursor.execute(statement)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/chad/.virtualenvs/site/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "userprofile_user" does not exist
It seems it is a problem with your migrations, try to add this to your settings in order to by pass them during tests:
class DisableMigrations(object):
def __contains__(self, item):
return True
def __getitem__(self, item):
return "notmigrations"
TESTS_IN_PROGRESS = False
if 'test' in sys.argv[1:]:
logging.disable(logging.CRITICAL)
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
DEBUG = False
TEMPLATE_DEBUG = False
TESTS_IN_PROGRESS = True
MIGRATION_MODULES = DisableMigrations()
I have a model, and I'm trying to add a foreignkey field to it.
This is the field definition:
part_of_speech = models.ForeignKey('PartOfSpeech', help_text=_('Translation | part_of_speech | help_text'), verbose_name = _('Translation','part_of_speech'))
When I try to perform the makemigrations command, I get the following error:
Migrations for 'dictionary':
0024_translation_part_of_speech.py:
- Add field part_of_speech to translation
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 143, in handle
self.write_migration_files(changes)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 171, in write_migration_files
migration_string = writer.as_string()
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/db/migrations/writer.py", line 146, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/db/migrations/writer.py", line 104, in serialize
_write(arg_name, arg_value)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/db/migrations/writer.py", line 74, in _write
arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/db/migrations/writer.py", line 354, in serialize
return cls.serialize_deconstructed(path, args, kwargs)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/db/migrations/writer.py", line 248, in serialize_deconstructed
arg_string, arg_imports = cls.serialize(arg)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/db/migrations/writer.py", line 276, in serialize
value = force_text(value)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/utils/encoding.py", line 92, in force_text
s = six.text_type(s)
File "/Users/user/.virtualenvs/env2/lib/python2.7/site-packages/django/utils/functional.py", line 141, in __text_cast
return func(*self.__args, **self.__kw)
TypeError: ugettext() takes exactly 1 argument (2 given)
The help text declaration (the call to ugetttext) is formatted improperly. To solve this, change this:
verbose_name = _('Translation','part_of_speech')
to this:
verbose_name = _('Translation | part_of_speech')
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
I've tried to build the simplest possible form in Sprox using pyramid.
# model.py
class Allocation:
# some fields ...
class SproxForm(AddRecordForm):
__model__ = Allocation
sprox_form = SproxForm(DBSession)
# views.py
#view_config(route_name='sprox_add', renderer='templates/sprox.pt')
def sprox_form_add(request):
return {'form':sprox_form,'form_input':{}}
<!-- sprox.pt -->
<html>
<body>
<div tal:content="structure form(form_input)"/>
</body>
</html>
When I navigate to that view in the browser, I get
Traceback (most recent call last):
File "D:\prg\py2\lib\site-packages\pyramid_debugtoolbar-1.0.4-py2.7.egg\pyramid_debugtoolbar\panels\performance.py", line 69, in noresource_timer_handler
result = handler(request)
File "D:\prg\py2\lib\site-packages\pyramid\tweens.py", line 21, in excview_tween
response = handler(request)
File "D:\prg\py2\lib\site-packages\pyramid_tm-0.7-py2.7.egg\pyramid_tm\__init__.py", line 82, in tm_tween
reraise(*exc_info)
File "D:\prg\py2\lib\site-packages\pyramid_tm-0.7-py2.7.egg\pyramid_tm\__init__.py", line 63, in tm_tween
response = handler(request)
File "D:\prg\py2\lib\site-packages\pyramid\router.py", line 161, in handle_request
response = view_callable(context, request)
File "D:\prg\py2\lib\site-packages\pyramid\config\views.py", line 367, in rendered_view
context)
File "D:\prg\py2\lib\site-packages\pyramid\renderers.py", line 531, in render_view
return self.render_to_response(response, system, request=request)
File "D:\prg\py2\lib\site-packages\pyramid\renderers.py", line 561, in render_to_response
result = self.render(value, system_values, request=request)
File "D:\prg\py2\lib\site-packages\pyramid\renderers.py", line 557, in render
result = renderer(value, system_values)
File "D:\prg\py2\lib\site-packages\pyramid\chameleon_zpt.py", line 42, in __call__
result = self.template(**system)
File "D:\prg\py2\lib\site-packages\chameleon\template.py", line 125, in __call__
return self.render(**kwargs)
File "D:\prg\py2\lib\site-packages\chameleon\zpt\template.py", line 257, in render
return super(PageTemplate, self).render(**vars)
File "D:\prg\py2\lib\site-packages\chameleon\template.py", line 190, in render
raise_with_traceback(exc, tb)
File "D:\prg\py2\lib\site-packages\chameleon\template.py", line 172, in render
self._render(stream, econtext, rcontext)
File "sprox_3aacd319285f07641f9292cdee192301f3a0bccd.py", line 136, in render
File "D:\prg\py2\lib\site-packages\chameleon\zpt\template.py", line 261, in include
self._render(*args, **kwargs)
File "template_f352de36cd7e76f81188f12078004a91a152cf44.py", line 376, in render
File "sprox_3aacd319285f07641f9292cdee192301f3a0bccd.py", line 106, in __fill_content
File "D:\prg\py2\lib\site-packages\sprox\viewbase.py", line 113, in __call__
return self.display(*args, **kw)
File "D:\prg\py2\lib\site-packages\sprox\viewbase.py", line 119, in display
return self.__widget__.display(*args, **kw)
File "D:\prg\py2\lib\site-packages\tw2\core\widgets.py", line 438, in display
return self.generate_output(displays_on)
File "D:\prg\py2\lib\site-packages\tw2\core\widgets.py", line 475, in generate_output
mw,
File "D:\prg\py2\lib\site-packages\tw2\core\templating.py", line 204, in render
return callback(kwargs)
File "D:\prg\py2\lib\site-packages\tw2\core\templating.py", line 144, in <lambda>
return lambda kwargs: Markup(tmpl.render(**kwargs))
File "D:\prg\py2\lib\site-packages\mako\template.py", line 412, in render
return runtime._render(self, self.callable_, args, data)
File "D:\prg\py2\lib\site-packages\mako\runtime.py", line 766, in _render
**_kwargs_for_callable(callable_, data))
File "D:\prg\py2\lib\site-packages\mako\runtime.py", line 798, in _render_context
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File "D:\prg\py2\lib\site-packages\mako\runtime.py", line 824, in _exec_template
callable_(context, *args, **kwargs)
File "form_mak", line 49, in render_body
File "D:\prg\py2\lib\site-packages\tw2\core\widgets.py", line 436, in display
r.prepare()
File "D:\prg\py2\lib\site-packages\tw2\core\resources.py", line 165, in prepare
resources = rl['middleware'].resources
KeyError: 'middleware'
- Expression: "form(form_input)"
- Filename: d:\prg\py2\awsalloc2\awsalloc2\templates\sprox.pt
- Location: (9:28)
- Source: ... v tal:content="structure form(form_input)" />
^^^^^^^^^^^^^^^^
- Arguments: repeat: {...} (0)
renderer_name: templates/sprox.pt
req: <Request - at 0x46fceb8L>
form: <SproxForm - at 0x471cb38L>
request: <Request - at 0x46fceb8L>
renderer_info: <RendererHelper - at 0x4a3b7b8L>
context: <instance None at 0x4f93c88L>
form_input: {...} (0)
view: <function sprox_form_add at 0x4a3d278L>
I have no idea what your real problem is, but I threw together a little demo to demonstrate how to setup Sprox under Pyramid. It was somewhat painful and uses some idioms that I consider pretty outdated, including requiring Paste, SQLAlchemy < 0.8, Genshi, and ToscaWidgets < 2.0. Hope this helps.
If I had to guess, you aren't adding the middleware to your app.
app = tw.api.make_middleware(
app,
{
'toscawidgets.framework' : 'wsgi',
'toscawidgets.middleware.inject_resources' : True,
},
stack_registry=True,
)
https://github.com/mmerickel/pyramid_sprox_demo