Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
TypeError: Object of type 'Category'(model) is not JSON serializable

Model class:

class Category(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

The controller that works with model:

class AjaxLayoutView():

@login_required
def categories_ajax(request):
    categories = Category.objects.all()
    cats = serializers.serialize('json', categories)
    return HttpResponse(
        json.dumps(cats),
        content_type="application/json"
    )

TypeError: Object of type 'Category' is not JSON serializable But in response in JavaScript with next code:

    $.getJSON( "/categories/ajax/", function( json ) {
    var src = JSON.parse(json);
    console.log(src);
    var valuesFromCategorys = [];

    for(var i=0;i<src.length;i++)
      valuesFromCategorys[i] = src[i].fields.name;
    console.log(src);

  $('#patient_category').editable({
    type: 'select',
    title: 'Оберіть нову категорію',
    source: valuesFromCategorys,
    ajaxOptions: { type:'POST'},
    params: function(params) {
      var objRequest = {category: params.value, pk:params.pk};
      console.log(params.value);
      return objRequest;
    },
    success: function(response, newValue) {
       console.log(response);
    }
  })
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try to iterate over object and then make a list or dictionary . then try json.dumps we can not dumps object directly.

@login_required
def categories_ajax(request):
categories = Category.objects.all()

cats= json.dumps([(dict(row.items())) for row in categories])
return HttpResponse(
    json.dumps(cats),
    content_type="application/json"
)
over 4 years ago · Santiago Trujillo Report

0

Since your view is returning an array of objects, you can access any serialized value like this:

$.getJSON("/categories/ajax/", function(json) {
    var src = JSON.parse(json);
    for (var i = 0; i < src.length; i++) {
        var category = src[i];
        console.log(category.fields.<field_name>);
    }
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!