buzza

Django and ExtJS – how to make them work together?

So, the main issue here is JSON format of Ext.data.JsonStore and django.core.serializers.
The django serializer does not support to serialize json data with root =( At least I didn’t find any hint how to do this.
Now then, what I used on the django side:

def phones_all_json(request):
    phones = Phone.objects.all()
    json = '{root:%s,count:%s}' % (serializers.serialize('json', phones, use_natural_keys=True), phones.count())
    return HttpResponse(json, mimetype='application/json')

yeah, here you can see the usage of KISS (keep it simple, stupid) principle
And on the ExtJS side we just need to specify the format of data that we will process:

PhonesStore = Ext.extend(Ext.data.JsonStore, {
    constructor: function(cfg) {
        cfg = cfg || {};
        PhonesStore.superclass.constructor.call(this, Ext.apply({
            storeId: 'phonesStore',
            autoLoad: true,
            url: '/phones/',
            root: 'root',
            totalProperty: 'count',
            fields: [
                {
                    name: 'city',
                    mapping: 'fields.city'
                },
                {
                    name: 'number',
                    mapping: 'fields.number'
                },
                {
                    name: 'name',
                    mapping: 'fields.subscriber.name'
                },
                {
                    name: 'surname',
                    mapping: 'fields.subscriber.surname'
                }
            ]
        }, cfg));
    }
});
new PhonesStore();

And then you need specify this store id in your view object (like grid):

var phonesToGrid = new Ext.grid.GridPanel({
  sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
  xtype: 'grid',
  title: 'Выбирете кому звонить',
  store: 'phonesStore',
  flex: 1,
  columns: [
  {xtype: 'gridcolumn',dataIndex: 'number',header: 'Номер',sortable: true,width: 100},
  {xtype: 'gridcolumn',dataIndex: 'city',header: 'Город',sortable: true,width: 100},
  {xtype: 'gridcolumn',dataIndex: 'name',header: '�мя',sortable: true,width: 100},
  {xtype: 'gridcolumn',dataIndex: 'surname',header: 'Фамилия',sortable: true,width: 100,id: ''}
});

That’s all… ExtJS will make get request on /phones handler and will take json data with corret format that was specified in PhonesStore.

Add Comment Register

Leave a Reply


three + = 11