简体   繁体   中英

Django: <DjangoObject> is not JSON serializable

I have recently been playing around with django with my testapp and encountered a problem that I never encountered before and I would like to request some assistance in my problem

I have the following model:

class Courses_list(models.Model):
    abbreviation = models.CharField(max_length=100, unique=True)
    course = models.CharField(max_length=100, unique=True)

class Job(models.Model):
    job_Position = models.CharField(max_length=30, unique=True)

    def __unicode__(self):
        return self.job_Position

class Job_Posting(models.Model):
    fkey = models.OneToOneField("Job")

class Educational_Requirement(models.Model):
    fkey = models.ForeignKey('Job_Posting')
    course = models.ForeignKey('Courses_list')

And a form that look like this

class CourseField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
         return obj.Course

class SomeForm(ModelForm):
    course = CourseField(queryset=Educational_Requirement.objects.all())

Upon save I am getting: <Job: Job_PositionValue> is not JSON serializable

I am saving the form's data at:

class SomeModel(models.Model):
    course = models.CharField(max_length=50)

What am I doing wrong? What does the error means in regards to my problem? Many thanks.

EDIT

Here is the Traceback

Environment:


Request Method: POST
Request URL: http://localhost:8000/2/apply

Django Version: 1.8.2
Python Version: 2.7.10
Installed Applications:
('grappelli',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sessions.models',
 'frontend',
 'file_maintenance',
 'reports',
 'transactions',
 'admin_reorder',
 'admin_notifications',
 'django_twilio')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.models.User',
 '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',
 'admin_reorder.middleware.ModelAdminReorder')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  223.                 response = middleware_method(request, response)
File "C:\Python27\lib\site-packages\django\contrib\sessions\middleware.py" in process_response
  50.                         request.session.save()
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\db.py" in save
  58.         session_data=self.encode(self._get_session(no_load=must_create)),
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\base.py" in encode
  88.         serialized = self.serializer().dumps(session_dict)
File "C:\Python27\lib\site-packages\django\core\signing.py" in dumps
  90.         return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "C:\Python27\lib\json\__init__.py" in dumps
  250.         sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\lib\json\encoder.py" in encode
  207.         chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\lib\json\encoder.py" in iterencode
  270.         return _iterencode(o, 0)
File "C:\Python27\lib\json\encoder.py" in default
  184.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /2/apply
Exception Value: <Job: System Admin> is not JSON serializable

EDIT 2

It has nothing to do with my OP as I have no idea what caused it

I have found the problem, It was with my request.session I have no idea why but adding the str() with the value I am inserting did the trick: request.session['SessionName'] = str(myvalue)

My views after the fix:

def save_page(request, job_id):
    form = application_form(request.POST)
    if request.method == 'POST':
        cde = form.save(commit = False)
        ....
        request.session['SessionName'] = str(cde.SomeField)
        cde.save()

Without your view code, it's difficult to pinpoint your issue. However the error is pretty self explanatory. Try setting your Django object's attributes to a dictionary, then serializing that dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM