django model with only one CharField is not JSON serializable - python

I have a very basic 'Place' model:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
and I'm trying to review it using the app: https://github.com/diefenbach/django-reviews
When trying to add a review to certain Place object, in the app's views https://github.com/diefenbach/django-reviews/blob/master/reviews/views.py, it reaches te 'save' method and actually saves a record in the database. However it raises the following TypeError:
Environment:
Request Method: POST
Request URL: http://ec2-54-77-118-44.eu-west-1.compute.amazonaws.com:5000/reviews/add/11/1
Django Version: 1.6.5
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'places',
'reviews')
Installed Middleware:
('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 "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
199. response = middleware_method(request, response)
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/contrib/sessions/middleware.py" in process_response
38. request.session.save()
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in save
57. session_data=self.encode(self._get_session(no_load=must_create)),
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in encode
87. serialized = self.serializer().dumps(session_dict)
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/core/signing.py" in dumps
88. return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python2.7/json/__init__.py" in dumps
250. sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
207. chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
270. return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
184. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /reviews/add/11/1
Exception Value: <Place: Teteria India> is not JSON serializable
I don't understand why this error raises if I'm still not using any AJAX or JSON and as far as I could see neither does the reviews app's views. Does it have anything to do with the forms?
And anyway, how can it be that a model with only one CharField is not JSON serializable? Do I have to provide the serialization?
Thanks!

In the line 148, it store object in the session
request.session["last-rated-object"] = object
then perfoms a redirect to reviews_thank_you's view
def thank_you(request, template_name="reviews/thank_you.html"):
"""Displays a thank you page.
"""
if request.session.has_key("last-rated-object"):
object = request.session.get("last-rated-object")
del request.session["last-rated-object"]
else:
object = None
return render_to_response(template_name, RequestContext(request, {
"object" : object,
}))
It is returning the object without serialize it and i think here is the problem. Can you edit that view to return a serialize version of you object?

Related

TypeError: Object of type 'TopicSerializer' is not JSON serializable Django

Hi All I faced this issue while getting API response. I am using django==2.1.7. Below I am adding my code snippet
models.py
The model contains topic names(en,bn), taglist(string), and Bucket_id or topic_id
class Topics(models.Model):
id = models.AutoField(primary_key=True)
name_en = models.CharField(max_length=70, blank=False, default='')
name_bn = models.CharField(max_length=70, blank=False, default='')
tags = models.TextField(blank=False, default='')
bucket_id = models.IntegerField()
def set_tags(self, x):
self.tags = json.dumps(x)
def get_tags(self):
return json.loads(self.tags)
class Meta:
managed = True
db_table = 'follow_topics'
serialize.py
TopicSeializer used for JSON serialize the model
from rest_framework import serializers
from .models import Topics
class TopicSerializer(serializers.ModelSerializer):
class Meta:
model = Topics
fields = ['name_en','name_bn','tags', 'bucket_id']
views.py
get_topic function gives me the list of the topic from the model
#api_view(('GET',))
def get_topics(requests):
topic_id = requests.GET.get('topic_id', None)
post_data = Topics.objects.filter(bucket_id=topic_id)
serialize_data = TopicSerializer(post_data, many=True)
return Response({"status": "success", "data": serialize_data})
I got serializable error. This error looks frustrating for me. Please help me share some useful resource or way that I can fix this error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/feed/v1/get_topics?topic_id=2
Django Version: 2.1.7
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'rest_framework',
'feedv1']
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
154. response = response.render()
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/template/response.py" in render
106. self.content = self.rendered_content
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_context
688. 'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_content
424. content = renderer.render(data, accepted_media_type, renderer_context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
107. allow_nan=not self.strict, separators=separators
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/json.py" in dumps
28. return json.dumps(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py" in dumps
238. **kw).encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in encode
201. chunks = list(chunks)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
430. yield from _iterencode_dict(o, _current_indent_level)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode_dict
404. yield from chunks
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
437. o = _default(o)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/encoders.py" in default
68. return super(JSONEncoder, self).default(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in default
180. o.__class__.__name__)
Exception Type: TypeError at /feed/v1/get_topics
Exception Value: Object of type 'TopicSerializer' is not JSON serializable
You need to access the .data property of the serializer
return Response({"status": "success", "data": serialize_data.data})

TypeError while uploading image using REST api in OpenShift V3

I have a Django App that accept images through REST-api. I tested the api using POSTMAN locally, it's working perfect with image uploads. Later I deployed it on OpenShift V3 and when I tried the same for uploading process using POSTMAN , it's saying
Server Traceback
Environment:
Request Method: POST
Request URL: http://django-psql-persistent-sampledjangoex.44fs.preview.openshiftapps.com/myapp/sample/
Django Version: 1.9
Python Version: 3.5.1
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'welcome',
'rest_framework')
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
'whitenoise.middleware.WhiteNoiseMiddleware')
Traceback:
File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/opt/app-root/src/.local/lib/python3.5/site-packages/rest_framework/response.py" in rendered_content
71. ret = renderer.render(self.data, media_type, context)
File "/opt/app-root/src/.local/lib/python3.5/site-packages/rest_framework/renderers.py" in render
104. separators=separators
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/json/__init__.py" in dumps
237. **kw).encode(obj)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/json/encoder.py" in encode
199. chunks = self.iterencode(o, _one_shot=True)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/json/encoder.py" in iterencode
257. return _iterencode(o, 0)
File "/opt/app-root/src/.local/lib/python3.5/site-packages/rest_framework/utils/encoders.py" in default
64. return super(JSONEncoder, self).default(obj)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/json/encoder.py" in default
180. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /myapp/sample/
Exception Value: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06\x07\x07\x06\x08\n' is not JSON serializable
Here is the source Code of the Program
Note: I can do uploading process through DRF-Browsable api
First of all I would say thanks to #Raz. Actually the tool POSTMAN caused the issue. I tested the OpenShift-v3 api using Python's Request library. It's worked :)
Code I used;
import requests
from requests.auth import HTTPBasicAuth
url = 'http://django-psql-persistent-sampledjangoex.44fs.preview.openshiftapps.com/myapp/sample/'
filess = {'image': open('sampleImage.png', 'rb')}
r = requests.post(url,data={'name': 'value1', 'number': 12573474},auth=HTTPBasicAuth('admin', 'admin'),files=filess)

Attribute error queryset.filter() django

So I got a method in views.py that checks if a certain product is saved in the session variables. If this is the case then it will look up the ID of the product in mongodb in order to filter a queryset on a few attributes of this product. I have the following code:
def moederbordenComp(request,objectlijst):
objectlijst_filtered = objectlijst
if "processorenid" in request.session:
processor= Processoren.objects.get(id=request.session["processorenid"])
objectlijst_filtered = objectlijst.filter(Socket__icontains=processor.Socket)
if "behuizingenid" in request.session:
behuizing = Behuizingen.objects.get(id=request.session["behuizingenid"])
objectlijst_filtered = objectlijst.filter(Form_Factor__icontains=behuizing.Form_Factor)
if "geheugenid" in request.session:
geheugen = Geheugen.objects.get(id=request.session["geheugenid"])
objectlijst_filtered = objectlijst.filter(Geheugentype__icontains=geheugen.Geheugentype)
objectlijst_filtered = objectlijst.filter(Geheugentype__icontains=geheugen.Aantal)
if "hardeid" in request.session:
harde = Harde.objects.get(id=request.session["hardeid"])
objectlijst_filtered = objectlijst.filter(Hardeschijf_bus__icontains=harde.Hardeschijf_bus)
return objectlijst_filtered
So basically. If processorenid exists then filter the queryset called "objectlist" so that only the motherboards remain that contain the processor.Socket.
Now for the real issue:
whenever I remove the objectlijst_filtered and just return the objectlijst (so unfiltered, without doing anything) everything works fine. However if I try to return and then use objectlijst_filtered or even print objectlijst_filtered it raises the following error:'list' object has no attribute 'join'
This is the complete error traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/moederborden/
Django Version: 1.7
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'pcbuilder')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/robin/Work/School/A-Pc/Website/pcbuilder/views.py" in moederborden
728. moederbordenlijst = compatibility(request,moederbordenlijst)
File "/home/robin/Work/School/A-Pc/Website/pcbuilder/compatibility.py" in compatibility
6. objectlijst_filtered = moederbordenComp(request,objectlijst)
File "/home/robin/Work/School/A-Pc/Website/pcbuilder/compatibility.py" in moederbordenComp
34. print objectlijst_filtered
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/queryset.py" in __repr__
58. self._populate_cache()
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/queryset.py" in _populate_cache
93. self._result_cache.append(self.next())
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py" in next
1137. raw_doc = self._cursor.next()
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py" in _cursor
1182. self._cursor_obj = self._collection.find(self._query,
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py" in _query
1215. self._mongo_query = self._query_obj.to_query(self._document)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/visitor.py" in to_query
92. query = query.accept(QueryCompilerVisitor(document))
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/visitor.py" in accept
157. return visitor.visit_query(self)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/visitor.py" in visit_query
80. return transform.query(self.document, **query.query)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/transform.py" in query
87. value = field.prepare_query_value(op, value)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/fields.py" in prepare_query_value
106. value = re.escape(value)
File "/usr/lib/python2.7/re.py" in escape
214. return pattern[:0].join(s)
Exception Type: AttributeError at /moederborden/
Exception Value: 'list' object has no attribute 'join'
Any help would be greatly appreciated. I've used the filter method in several other parts of the project without any issues so I'm at a loss.
Thanks in advance.

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 attribute error: 'module' object has no attribute 'is_usable'

I got the following error when calling the url in Django.
It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are.
Thanks before for the help,
Robert
Environment:
Request Method: GET Request URL: http://localhost:8000/time/ Django Version: 1.2 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'djlearn.books'] 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.6/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args,
**callback_kwargs) File "/Users/rhenru/Workspace/django/djlearn/src/djlearn/../djlearn/views.py" in current_datetime
16. return render_to_response('current_datetime.html',{'current_date':now,}) File "/Library/Python/2.6/site-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args,
**kwargs), **httpresponse_kwargs) File "/Library/Python/2.6/site-packages/django/template/loader.py" in render_to_string
181. t = get_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in get_template
157. template, origin = find_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template
128. loader = find_template_loader(loader_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template_loader
111. if not func.is_usable:
Exception Type: AttributeError at /time/ Exception Value: 'module' object has no attribute 'is_usable'
It looks like Django is looking for a usable template loader, but is finding something in settings.TEMPLATE_LOADERS that isn't honoring the template loader function protocol (described briefly here.)
Is it possible that one of your recent changes was to either settings.TEMPLATE_LOADERS or to a custom template loader? If the latter, your template function needs an is_usable attribute, presumably set to True.

Categories