Trying to create an object with get_or_create(). The response hits, but it never successfully creates the object.
Python code:
class Note(models.Model):
user = models.ForeignKey(User)
topic = models.CharField(max_length=500, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
content = models.TextField(null=True, blank=True)
type = models.ForeignKey(NoteType, null=True, blank=True)
def __unicode__(self):
return self.topic
def post(request):
topic = request.POST['topic']
user = request.user
content = request.POST['content']
note_type = request.POST['type']
note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type)
return HttpResponseRedirect('/home/')
So the exception constantly hits and never creates the object. Urls are fine and I'm importing the model. Any reason why this object isn't being created? Theres no errors, it just redirects as normal.
traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/post/
Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'notes')
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 "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "c:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "c:\Users\Alana\project-fridge\notes\views.py" in post_note
34. note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type)
File "c:\Python27\lib\site-packages\django\db\models\manager.py" in get_or_create
146. return self.get_query_set().get_or_create(**kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in get_or_create
470. return self.get(**lookup), False
File "c:\Python27\lib\site-packages\django\db\models\query.py" in get
379. clone = self.filter(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in filter
655. return self._filter_or_exclude(False, *args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
673. clone.query.add_q(Q(*args, **kwargs))
File "c:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1266. can_reuse=used_aliases, force_having=force_having)
File "c:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_filter
1197. connector)
File "c:\Python27\lib\site-packages\django\db\models\sql\where.py" in add
71. value = obj.prepare(lookup_type, value)
File "c:\Python27\lib\site-packages\django\db\models\sql\where.py" in prepare
339. return self.field.get_prep_lookup(lookup_type, value)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in get_prep_lookup
143. return self._pk_trace(value, 'get_prep_lookup', lookup_type)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in _pk_trace
216. v = getattr(field, prep_func)(lookup_type, v, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_lookup
322. return self.get_prep_value(value)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
555. return int(value)
Exception Type: ValueError at /post/
Exception Value: invalid literal for int() with base 10: 'text'
Thank you for your help in advance.
I assume that you are storing a list of various Note Types in the NoteType model...
To make this code work, you are first going to need to get one of them from that model and then set use that when creating your new note
note_type = request.POST['type']
note_type_orm = NoteType.objects.get(type=note_type)
note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type_orm)
Notice the change in the get_or_create that I am now using the note_type_orm and not just the note_type (which is just a string)
Related
I have the following model:
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000)
cvfile = models.FileField()
I am trying to write the contents of cvfile to cv when the user submits the name and file from the form. I'm sure this can be done as the file and text field will be in the same object. The file will always be .txt so I assume a simple .read() can be performed.
Should I have a function that the form calls to perform this? If so how can this be done?
def writeCV(self):
get_text = cvfile.open().read()
#write to cv field somehow
return self.cv
I am using django 1.9
Traceback from Messaoud's answer:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/cleaner/clean/add/
Django Version: 1.9
Python Version: 3.6.4
Installed Applications:
['cleaner.apps.CleanerConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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 "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
255. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
221. return self.form_valid(form)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in form_valid
200. self.object = form.save()
File "C:\Python\Python36-32\lib\site-packages\django\forms\models.py" in save
451. self.instance.save()
File "C:\Users\barry\Desktop\College\Year 4\Semester 2\cvCleaner\cvcleaner\cleaner\models.py" in save
11. get_text = self.cvfile.open().read()
Exception Type: AttributeError at /cleaner/clean/add/
Exception Value: 'NoneType' object has no attribute 'read'
You can do this by overriding save method in your Model
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000, blank = True, null = True)
cvfile = models.FileField()
def save(self, *args, **kwargs):
get_text = self.cvfile.open().read()
self.cv = get_text
super(Clean, self).save(*args, **kwargs) # Call the "real" save() method.
Or by Using post_save signal
def writeCV(sender, instance, **kwargs):
get_text = instance.cvfile.open().read()
instance.cv = get_text
instance.save()
post_save.connect(writeCV, sender=Clean)
I'm using Cloudinary in my Django application to store and serve images that users upload in one view of my site. The images are getting uploaded and shown correctly; however, in my UpdateView when a user checks 'clear' to remove the previous image and then submits the form this error is shown:
TypeError: expected string or bytes-like object
The error page in the browser also shows these highlighted messages:
...\lib\site-packages\cloudinary\models.py in to_python
return self.parse_cloudinary_resource(value) ...
...\lib\site-packages\cloudinary\models.py in parse_cloudinary_resource
m = re.match(CLOUDINARY_FIELD_DB_RE, value) ...
...\AppData\Local\Programs\Python\Python36-32\lib\re.py in match
return _compile(pattern, flags).match(string)
These are what my model, view and form look like:
models.py:
class Item(models.Model):
name = models.CharField(max_length=255)
image1 = CloudinaryField('image', blank=True, null=True)
views.py
class ItemUpdateView(LoginRequiredMixin, UpdateView):
model = models.Item
form_class = forms.ItemForm
forms.py
class ItemForm(forms.ModelForm):
image1 = CloudinaryFileField(
required=False,
options = {'crop': 'limit', 'width': 546, 'height': 1000,})
class Meta:
model = models.Item
fields = ("image1", "name")
I think Cloudinary is still expecting something when the field's value is empty. I have looked at the docs and searched the web and I just can't figure out how to fix this.
Edit: I checked my admin and tried to edit an item from there and got the same error when I checked the 'clear' checkbox and hit Save. So it seems that the problem is with how I've created the image1 field on my model, since the Admin view would only be relying on that. But I still don't know how to fix it.
Edit2: Full Traceback of when I check 'clear' on the image field and click Save, from the admin:
Environment:
Request Method: POST Request URL:
http://127.0.0.1:8000/admin/items/item/4/change/
Django Version: 1.11.1 Python Version: 3.6.1 Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'cloudinary',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.twitter',
'haystack',
'items']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"D:\projects\django\gia\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)
File
"D:\projects\django\gia\lib\site-packages\django\core\handlers\base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"D:\projects\django\gia\lib\site-packages\django\core\handlers\base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\views\decorators\cache.py"
in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\sites.py"
in inner
224. return view(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in change_view
1511. return self.changeform_view(request, object_id, form_url, extra_context)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in _wrapper
67. return bound_func(*args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in bound_func
63. return func.get(self, type(self))(*args2, **kwargs2)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in changeform_view
1408. return self._changeform_view(request, object_id, form_url, extra_context)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in _changeform_view
1440. if form.is_valid():
File "D:\projects\django\gia\lib\site-packages\django\forms\forms.py"
in is_valid
183. return self.is_bound and not self.errors
File "D:\projects\django\gia\lib\site-packages\django\forms\forms.py"
in errors
175. self.full_clean()
File "D:\projects\django\gia\lib\site-packages\django\forms\forms.py"
in full_clean
386. self._post_clean()
File "D:\projects\django\gia\lib\site-packages\django\forms\models.py"
in _post_clean
396. self.instance.full_clean(exclude=exclude, validate_unique=False)
File
"D:\projects\django\gia\lib\site-packages\django\db\models\base.py" in
full_clean
1226. self.clean_fields(exclude=exclude)
File
"D:\projects\django\gia\lib\site-packages\django\db\models\base.py" in
clean_fields
1268. setattr(self, f.attname, f.clean(raw_value, self))
File
"D:\projects\django\gia\lib\site-packages\django\db\models\fields__init__.py"
in clean
601. value = self.to_python(value)
File "D:\projects\django\gia\lib\site-packages\cloudinary\models.py"
in to_python
74. return self.parse_cloudinary_resource(value)
File "D:\projects\django\gia\lib\site-packages\cloudinary\models.py"
in parse_cloudinary_resource
50. m = re.match(CLOUDINARY_FIELD_DB_RE, value)
File
"C:\Users\samee\AppData\Local\Programs\Python\Python36-32\lib\re.py"
in match
172. return _compile(pattern, flags).match(string)
Exception Type: TypeError at /admin/items/item/4/change/ Exception
Value: expected string or bytes-like object
Maybe a bit late here but I had the same issue and in my search for a solution I stumbled upon this.
What I worked out was that the validation method was still looking for a object that no longer existed. By clicking the clear button you effectively remove it from the post back. Validation is set up by default to flag this up because it is trying to clea (validate) something that is now no longer there.
You get around it quite easily. Simply create the clean method that the is_valid method invokes. The picture wont be there anymore so just return None. Here is a code example:
From my is_valid():
if request.method == 'POST':
if picture_form_set.is_valid():
which in turn calls the clean methods, so create one for the Cloudaniry field:
def clean_picture(self):
return self.cleaned_data['picture'] or None
Hope that helps
The issue is with the to_python method in the the CloudinaryField, it expects the value of image to a none but instead gets a False.
Solution create a new field that inherits from the parent CloudinaryField apply the fix and use that as your models field.
Solution by Marco Silva on this github issue, https://github.com/cloudinary/pycloudinary/issues/98.
class CloudinaryFieldFix(CloudinaryField):
def to_python(self, value):
if value is False:
return value
else:
return super(FixCloudinaryField, self).to_python(value)
I'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.
my error page and code
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'blog',
'account',
'taggit',
'friendship',
'rest_framework']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/decorators.py" in handler
52. return func(*args, **kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
37. return Response(serializer.data)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
700. ret = super(ListSerializer, self).data
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in <listcomp>
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/relations.py" in get_attribute
157. return get_attribute(instance, self.source_attrs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/fields.py" in get_attribute
83. instance = getattr(instance, attr)
Exception Type: AttributeError at /blog/
Exception Value: 'str' object has no attribute 'author'
I wonder how to make serializers.py codes.
I already studied : http://www.django-rest-framework.org/api-guide/relations/
But I don't understand what I should do. Where should I put serializers.py?
And how to make my serializers code? Or maybe models.ForienKey is unavailable on using DRF?
blog/views.py
#api_view(['GET'])
def post_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
i=1
while i:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
list_total = str(',' + ' list_i')
post_list = list(chain(list_total))
if len(post_list) >= 0 :
break
serializer = PostSerializer(post_list, many=True)
return Response(serializer.data)
This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.
So, in your post_list view, you build up a list (also called post_list) which is populated by a list of strings. Then you try and put it through the PostSerializer, which of course is expecting a queryset of Posts.
I'm not sure what the point of the list is; seems like you should be passing the Posts directly to the serializer.
I am trying to get the UUIDField to work in python django using the following model:
class Ticket(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50)
However when I try adding an instance of the model to the database it returns the following error:
TypeError at /tickets/
coercing to Unicode: need string or buffer, UUID found
The documentation of UUIDField is really short and doesn't really help me.
edit: I did import uuid and here is the full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/tickets/
Django Version: 1.8.5
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'events',
'rest_framework')
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',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
663. ret = super(ListSerializer, self).data
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
228. self._data = self.to_representation(self.instance)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
603. self.child.to_representation(item) for item in iterable
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
461. ret[field.field_name] = field.to_representation(attribute)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in to_representation
356. name = self.get_name(value)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in get_name
276. return six.text_type(obj)
Exception Type: TypeError at /tickets/
Exception Value: coercing to Unicode: need string or buffer, UUID found
Edit 2: My serializer looks like this:
class TicketSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Ticket
fields = ('url', 'id', 'name')
Edit 3:
I found the error. I made a mistake in my model. My unicode looked like this:
def __unicode__(self):
return self.id
And of course this does not work.
Probably you should use something like this:
def __unicode__(self):
return str(self.id)
When I try and save (using the Django standard admin interface) I get the following error...
TypeError at /admin/web/campaign/dc6eb21f-87fa-462f-88af-416cf6be37f6/
get_db_prep_value() got an unexpected keyword argument 'connection'
Could someone explain this to me, why and maybe a possible solution? I'm assuming it is something to do with my custom HibernateBooleanField field.
Full error and details below.
Error
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/web/campaign/dc6eb21f-87fa-462f-88af-416cf6be37f6/
Django Version: 1.4.2
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.flatpages',
'django.contrib.messages',
'django.contrib.staticfiles',
'grappelli.dashboard',
'grappelli',
'django.contrib.admin',
'django.contrib.admindocs',
'web')
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 "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/Library/Python/2.7/site-packages/django/db/transaction.py" in inner
209. return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in change_view
1054. self.save_model(request, new_object, form, True)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in save_model
709. obj.save()
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base
529. rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update
560. return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
986. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
808. sql, params = self.as_sql()
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
951. val = field.get_db_prep_save(val, connection=self.connection)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
292. prepared=False)
Exception Type: TypeError at /admin/web/campaign/dc6eb21f-87fa-462f-88af-416cf6be37f6/
Exception Value: get_db_prep_value() got an unexpected keyword argument 'connection'
model
class Campaign(models.Model):
campaignid = models.CharField(max_length=255, primary_key=True, db_column='campaignID')
name = models.CharField(max_length=105)
active = HibernateBooleanField(default=False)
created = models.DateTimeField()
modified = models.DateTimeField(null=True, blank=True)
companyid = models.ForeignKey(Company, null=True, db_column='companyID', blank=True)
class Meta:
db_table = u'campaign'
def __unicode__(self):
return self.name
class HibernateBooleanField(models.BooleanField):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "HibernateBooleanField"
def db_type(self):
return 'bit(1)'
def to_python(self, value):
if value in (True, False): return value
if value in ('t', 'True', '1', '\x01'): return True
if value in ('f', 'False', '0', '\x00'): return False
def get_db_prep_value(self, value):
return 0x01 if value else 0x00
Yes, that would be a fair assumption. As you can see from the source code, the signature of that method is def get_db_prep_value(self, value, connection, prepared=False), so any subclass needs to either expect the same arguments or take *args, **kwargs.
Daniel Roseman pretty much answered this, but I will state it in another way and use more words so that you hopefully understand. For custom fields in Django 1.4.x, your custom field's get_db_prep_value function MUST NOW ACCEPT 4 parameters. In Django 1.2, the Django developers introduced multiple database support. In Django 1.4.x, the developers REMOVED code that would've allowed your function declaration to work.
So what do you need to do? You need to redefine HibernateBooleanField.get_db_prep_value to accept the extra arguments. Change your get_db_prep_value function like I have below, and it will work :)
def get_db_prep_value(self, value, connection, prepared=False):
return 0x01 if value else 0x00
Django documentation reference: https://docs.djangoproject.com/en/1.2/howto/custom-model-fields/#django.db.models.Field.get_db_prep_value