Django administration Site. 'Delete multiple objects' produces ValidationError - python

When attempting to delete multiple rows, which have a one to one relationship with two other tables I received the following error:
['“March 21, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.']
The models are set up as such:
class Media(models.Model):
date = models.DateField(primary_key=True, unique=True)
received_url = models.CharField(max_length=200, blank=True, null=True)
class Api(models.Model):
media = models.OneToOneField(Media, on_delete=models.CASCADE)
request_url = models.CharField(max_length=200)
class Text(models.Model):
media = models.OneToOneField(Media, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
copyright = models.CharField(max_length=200, blank=True, null=True)
I am trying to delete the items in the Home › My_App_Main › Medias › Delete multiple objects from the Django administration site. Which presents me with the following:
Are you sure?
Are you sure you want to delete the selected medias? All of the following objects and their related items will be deleted:
Summary
Medias: 2
Apis: 2
Texts: 2
Objects
Media: 2022-03-21
Api: 2022-03-21
Text: 2022-03-21
Media: 2022-03-20
Api: 2022-03-20
Text: 2022-03-20
I then click Yes, I'm Sure
Which triggers then triggers the error.
Checking the POST request in the network log for the browser I noted the dates appear to be in the wrong format:
_selected_action […]
0 "March+21,+2022"
1 "March+20,+2022"
action "delete_selected"
post "yes"
I tried in both Firefox and Chrome.
Checking the data from the Django shell nothing stands out as incorrect. The data comes back as expected:
>>> for field in Media.objects.all():
... print(f'{type(field.date)}({field.date})')
...
<class 'datetime.date'>(2022-03-21)
<class 'datetime.date'>(2022-03-20)
>>> for field in Text.objects.all():
... print(f'{type(field.media.date)}({field.media.date})')
...
<class 'datetime.date'>(2022-03-21)
<class 'datetime.date'>(2022-03-20)
>>> for field in Api.objects.all():
... print(f'{type(field.media.date)}({field.media.date})')
...
<class 'datetime.date'>(2022-03-21)
<class 'datetime.date'>(2022-03-20)
It seems to me it could something to do with the Django administration site doing something odd with the date format? Or perhaps it's the browser defaults that are the issue? Or maybe even something I need to set in the Django settings file? If that's the case how would one go about changing that behaviour?
The error as it comes back in the browser:
ValidationError at /admin/my_app_main/media/
['“March 21, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.']
Request Method: POST
Request URL: http://127.0.0.1:11111/admin/my_app_main/media/
Django Version: 4.0.3
Exception Type: ValidationError
Exception Value:
['“March 21, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.']
Exception Location: /home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/fields/init.py, line 1370, in to_python
Python Executable: /home/user/.pyenv/versions/my_app/bin/python
Python Version: 3.8.2
Python Path:
['/home/user/git/user/my_app',
'/home/user/git/user/my_app',
'/home/user/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/lib/python/debugpy/_vendored/pydevd',
'/home/user/.pyenv/versions/3.8.2/lib/python38.zip',
'/home/user/.pyenv/versions/3.8.2/lib/python3.8',
'/home/user/.pyenv/versions/3.8.2/lib/python3.8/lib-dynload',
'/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages',
'/home/user/git/user/my_app/apps']
Server time: Mon, 21 Mar 2022 14:40:59 +0000
Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:11111/admin/my_app_main/media/
Django Version: 4.0.3
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'apps.my_app_main.apps.MyAppMainConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/contrib/admin/options.py", line 683, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/utils/decorators.py", line 133, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 242, in inner
return view(request, *args, **kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper
return bound_method(*args, **kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/utils/decorators.py", line 133, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1983, in changelist_view
response = self.response_action(
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1586, in response_action
queryset = queryset.filter(pk__in=selected)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1466, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1496, in _add_q
child_clause, needed_inner = self.build_filter(
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1242, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/lookups.py", line 27, in __init__
self.rhs = self.get_prep_lookup()
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/lookups.py", line 275, in get_prep_lookup
rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1404, in get_prep_value
return self.to_python(value)
File "/home/user/.pyenv/versions/my_app/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1370, in to_python
raise exceptions.ValidationError(
Exception Type: ValidationError at /admin/my_app_main/media/
Exception Value: ['“March 21, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.']

I would recommend not using DateField as a primary key. Or is there any reason to do that? You can keep unique=True anyway if you want to check there are no two instances with the same date.
class Media(models.Model):
date = models.DateField(unique=True)
received_url = models.CharField(max_length=200, blank=True, null=True)

Related

Error in import FloatField, using django-import-export

I am using django-import-export for import csv file. I have a FloatField in my model :
models.py
purchase_price = models.FloatField(null=True, blank=True)
When I import csv file with blank value, it throws an error :
ValueError at /admin/csv_imp/book/process_import/
could not convert string to float:
Request Method: POST
Request URL: http://localhost:8000/admin/csv_imp/book/process_import/
Django Version: 1.7.1
Exception Type: ValueError
Exception Value:
could not convert string to float:
Exception Location: /home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1550
Python Executable: /home/bgdev/Desktop/virtualenvs/django17/bin/python
Python Version: 2.7.6
Python Path:
['/home/bgdev/Desktop/virtualenvs/django17/test_pro',
'/home/bgdev/Desktop/virtualenvs/django17/src/admin-bootstrap',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/plat-i386-linux-gnu',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-tk',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-old',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages',
'/home/bgdev/Desktop/virtualenvs/django17/lib/python2.7/site-packages']
Server time: Tue, 9 Dec 2014 05:33:36 +0000
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/csv_imp/book/process_import/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('bootstrap_admin',
'import_export',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'csv_imp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
204. return view(request, *args, **kwargs)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/admin.py" in process_import
130. raise_errors=True)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in import_data
359. six.reraise(*sys.exc_info())
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in import_data
345. self.save_instance(instance, real_dry_run)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/import_export/resources.py" in save_instance
163. instance.save()
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in save
591. force_update=force_update, update_fields=update_fields)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
619. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
681. forced_update)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_update
725. return filtered._update(values) > 0
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/query.py" in _update
600. return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1004. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
775. sql, params = self.as_sql()
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
969. val = field.get_db_prep_save(val, connection=self.connection)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
627. prepared=False)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
619. value = self.get_prep_value(value)
File "/home/bgdev/Desktop/virtualenvs/django17/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
1550. return float(value)
Exception Type: ValueError at /admin/csv_imp/book/process_import/
Exception Value: could not convert string to float:
I found similar issue with and IntegerField. Being the last column in the csv file, it turns out that I was introducing an extra End of Line character in the dataset, even if the field had an empty value. Removing the EOL character from every line before adding it to the dataset fixed the issue:
for line in file.readlines():
line = line.rstrip('\r\n')
dataset.append(tuple(item for item in line.split(',')))
This link will show you what null and blank do: differentiate null=True, blank=True in django
If you can arrange your csv file to have all of the null values at the end, you can just remove the commas. That might work. Or perhaps create a temporary model that assigns those fields to a Charfield. Then copy appropriate fields to your final model
This is untested:
update <table> set <field> = 0 where id in (select id from <table> where <field> = "");
Fill in your table name and the field name as appropriate. You can run this from your sql command line program

Uploading to Google Cloud Storage from Django on App Engine

I'm using Django 1.5 on Google App Engine and I'm trying to upload files to Google Cloud Storage. I'm using the gcs the library and have written a custom file upload handler that I've registered in settings.py as my only file uploader. I can see my file being correctly uploaded in the blobstore viewer in my development environment but once form.save() is called in views.py I get an exception thrown saying that it's a read only file system? I know Google App Engine doesn't allow access to the file system which is why I'm using GCS in the first place!
Is there something I need to do to stop Django from trying to save the file to disk?
The relevant code is attached in this gist.
Thanks :)
Stack Trace:
Environment:
Request Method: POST
Request URL: http://localhost:8080/cms/media/add
Django Version: 1.5
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.messages',
'api',
'cms',
'frontend')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/Users/james/Dropbox/University/Year 4/Advanced Development/assignment/cms/views.py" in media_add_or_edit
44. form.save()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/forms/models.py" in save
370. fail_message, commit, construct=False)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/forms/models.py" in save_instance
87. instance.save()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/query.py" in insert_query
1673. return query.get_compiler(using=using).execute_sql(return_id)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/sql/compiler.py" in execute_sql
936. for sql, params in self.as_sql():
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/sql/compiler.py" in as_sql
894. for obj in self.query.objs
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/fields/files.py" in pre_save
250. file.save(file.name, file, save=False)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/db/models/fields/files.py" in save
86. self.name = self.storage.save(name, content)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/core/files/storage.py" in save
48. name = self._save(name, content)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/core/files/storage.py" in _save
198. fd = os.open(full_path, flags, 0o666)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/devappserver2/python/stubs.py" in fake_open
71. raise OSError(errno.EROFS, 'Read-only file system', filename)
Exception Type: OSError at /cms/media/add
Exception Value: [Errno 30] Read-only file system: u'/Users/james/Dropbox/University/Year 4/Advanced Development/assignment/IMG_0746.jpg'
I eventually solved this by moving the FileField from my Model into my ModelForm like so:
# Used for uploading media that forms part of a story
class Media(models.Model):
title = models.CharField(max_length=100)
type = models.CharField(max_length=5, choices=MEDIA_TYPES)
content = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
# Used to convert the media model to a form in the cms
class MediaForm(forms.ModelForm):
file = forms.FileField()
class Meta:
model = Media
# Don't show the date created field because we want that to be set automatically
exclude = ('date_created', 'content',)
I'm sure I tried that before but it appears to have fixed my issue, hopefully this might help someone else who runs into the same problem.

django when adding data from admin interface: TypeError at admin/... unicode object not callable

I'm getting an error when trying to save to the following model using the admin interface:
models.py
class Answer(models.Model):
a = models.TextField(primary_key=True)
gloss = models.TextField(blank=True)
clean = models.TextField(blank=True)
count = models.IntegerField(blank=True)
p = models.IntegerField(blank=True)
def __unicode__(self):
return u"%s" % self.a
class Meta:
db_table = u'answers'
here's the error message that shows up on the admin interface:
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/emotions/answer/add/
Django Version: 1.4 pre-alpha SVN-16322
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'emo20qBrowser.emotions']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/abe/bin/django-trunk/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/options.py" in wrapper
316. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/views/decorators/cache.py" in _wrapped_view_func
77. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/home/abe/bin/django-trunk/django/db/transaction.py" in inner
211. return func(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/options.py" in add_view
871. if form.is_valid():
File "/home/abe/bin/django-trunk/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/home/abe/bin/django-trunk/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/home/abe/bin/django-trunk/django/forms/forms.py" in full_clean
269. self._post_clean()
File "/home/abe/bin/django-trunk/django/forms/models.py" in _post_clean
331. self.instance.clean()
Exception Type: TypeError at /admin/emotions/answer/add/
Exception Value: 'unicode' object is not callable
Okay, I think I figured it out... I'm using a variable/column called "clean". Django's admin interface has a method called "clean()" also, which does some kind of validation. It appears that there was some kind of naming conflict so I changed the variable to name to "cleaned" and then to make sure that it knows what database field to use (I'm using a legacy/preexisting db), I added a db_column option:
cleaned = models.TextField(blank=True,db_column="clean")
It would have been nice to know that "clean" was a reserved identifier in django but at least I only wasted half a day on this django stuff which ostensibly makes database operations easier. To be fair, I just started django this morning and if I would have found and answer on stackoverflow it would have been a breeze to fix.
If anyone knows a better way to handle this, let me know...

Set ModelForm integer field as unrequired

I currently have a ModelForm set up in Django, but would like to make one of the fields of the form unrequired. Here's my forms.py:
from django.forms import ModelForm
from add_flair.models import User
class UserForm(ModelForm):
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['year'].required = False
So I figured out how to override the 'required' attribute of my 'year' field, but when I go to submit a form with no year, I get:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:9999/flair/add/
Django Version: 1.3
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'project.add_flair']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/coreyf/dev/reddit-calpoly-addflair/project/../project/add_flair/views.py" in add
14. save_user(form, confirm_num)
File "/home/coreyf/dev/reddit-calpoly-addflair/project/../project/add_flair/views.py" in save_user
42. user.save()
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/base.py" in save_base
543. for f in meta.local_fields if not isinstance(f, AutoField)]
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
28. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
28. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/__init__.py" in get_db_prep_save
276. return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/__init__.py" in get_db_prep_value
271. value = self.get_prep_value(value)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/__init__.py" in get_prep_value
876. return int(value)
Exception Type: ValueError at /flair/add/
Exception Value: invalid literal for int() with base 10: ''
I'm assuming that int() is trying to parse an empty value and throwing an error. Is there any way to fix this? Is there a better way of making a field from a ModelForm unrequired?
Add blank=True, null=True to your field declaration im models.py (and don't forget to reflect this change in DB, by migration or manually).

Django: FieldError cannot resolve keyword '___' into a field

I'm having a FieldError.
I have a model:
class Foo(models.Model):
__bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True)
def get_bar(self):
return cPickle.loads(str(self.__bar))
def set_bar(self, values):
self.__bar = cPickle.dumps(values)
bar = property(get_bar, set_bar)
I have registered it with the admin in admin.py:
admin.site.register(Foo)
When I runserver and go to /admin, I see Foo in the list. If I click "Add", it works fine, showing the form to add a new Foo. However, if I click "save and add another" or "change" or "Foos", I get a FieldError
FieldError at /admin/appname/Foo/
Cannot resolve keyword '_Foo' into field. Choices are: _Foo__bar, appname
The traceback is:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/appname/foo/
Django Version: 1.2.4
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'pagination',
'apps.appname']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in wrapper
265. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
78. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
190. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapper
21. return decorator(bound_func)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in bound_func
17. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in changelist_view
1097. 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in __len__
80. self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in iterator
271. for row in compiler.results_iter():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in results_iter
677. for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
722. sql, params = self.as_sql()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in as_sql
57. ordering, ordering_group_by = self.get_ordering()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in get_ordering
346. self.query.model._meta, default_order=asc):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in find_ordering_name
375. opts, alias, False)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in setup_joins
1215. "Choices are: %s" % (name, ", ".join(names)))
Exception Type: FieldError at /admin/appname/foo/
Exception Value: Cannot resolve keyword '_Foo' into field. Choices are: _Foo__bar, appname
What could be going on here? I did some searching, and I found similar errors but they seem to have something to do with many-to-many fields, of which I have none. There are other models that reference this one as a foreign key, but that seems unlikely to cause the problem.
Because you've prefixed __bar with two underscores, Python is performing name mangling (doc link) in an attempt to enforce private access to the variable.
Private variables, of course, don't exist in Python, but by using the double-underscore convention you've asked Python to reformat __bar as _(classname)__bar, which is why Django is telling you that "Choices are: _Foo__bar...".
If you wish to signal that bar shouldn't be used outside out the class, I'd recommend the single-underscore notation (also discussed at the link above), which should solve the field issue you're experiencing as single-underscore prefixes are not name mangled.

Categories