Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

258
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda