0

I would like to create a simple Django application with Ext JS interface. Task: The user enters data into a database using forms and sees the database upgrade. It has been done to solve the problem as follows. Written Django application.

views.py:

def addProduct(request):
if request.method == 'POST':
    form = ProductForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        product_name = data['product_name']
        product_price = data['product_price']
        Products.objects.create(name=product_name, price=product_price)
else:
    form = ProductForm()
return render(request, 'addProduct.html', {
    'ProductsList': Products.objects.all(),
    'form': form,
    # 'Title': 'Range of products',
    # 'product_name': 'type product name here',
})

template:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ Title }}</title>
</head>
<body>
<table>
    <tr>
        <th>Name</th>
        <th>Product</th>
    </tr>
    {% for current in ProductsList %}
        <tr>
            <td>{{ current.name }}</td>
            <td>{{ current.price }}</td>
        </tr>
    {% endfor %}
</table>

<form action="check/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="ADD" />
</form>

</body>
</html>

forms.py:

class ProductForm(forms.Form):
    product_name = forms.CharField(max_length=100)
    product_price = forms.IntegerField()

models.py:

class Products(models.Model):
    name = models.CharField(max_length=30)
    price = models.IntegerField()

This works well.

Result

Now I would like to use Ext.grid.Panel component from Ext JS to render table. Question: How do I transfer data from Django to Ext JS?

UPDATE

I wrote a simple grid, but it turns out the table is empty. What am I doing wrong?

    Ext.onReady(function () {
        Ext.define('Products', {
            extend: 'Ext.data.Model',

            fields: [{
                name: 'Name',
                type: 'string'
            }, {
                name: 'Price',
                type: 'int'
            }]
        });

        var store = Ext.create('Ext.data.Store', {
            model: 'Products',
            autoLoad: true,
            proxy: {
                type: 'rest',
                url: 'http://127.0.0.1:8000/products/',
                reader: {
                    type: 'json'
                }
            }
        });

        Ext.create('Ext.grid.Panel', {
            title: 'Products',
            height: 200,
            width: 400,
            store: store,
            columns: [{
                header: 'Name',
                dataIndex: 'Name'
            }, {
                header: 'Price',
                dataIndex: 'Price'
            }],
            renderTo: Ext.getBody()
        });


    });

I also updated the Django project using Django Rest Framework for REST technology:

class ProductsList(generics.ListCreateAPIView):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializer

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializer
JSON C11
  • 11,272
  • 7
  • 78
  • 65
Sergey Sigaev
  • 100
  • 2
  • 10

2 Answers2

0

Use ajax.

just like this:

$('#likes').click(function () {
    var catid;
    catid = $(this).attr("data-catid");
    $.get('/rango/like_category/', {category_id: catid}, function (data) {
        $('#like_count').html(data);
        $('#likes').hide();
    });
});
bot
  • 1
  • 2
0

I see two ways: 1) Make special server action, that will be return JSON-based view. On main template create Ext.grid.Grid with remote store, that will request data from server action, that returns JSON. It's mostly usable case. Look here example: http://docs.sencha.com/extjs/6.2.0/modern/Ext.grid.Grid.html - grid http://docs.sencha.com/extjs/6.2.0/modern/Ext.data.Store.html - store

2) Make html table with data, and transform it to ExtJS grid like here: http://examples.sencha.com/extjs/6.2.0/examples/classic/grid/binding.html

Selmaril
  • 746
  • 5
  • 11
  • Thank you for your help. I've updated the post, see section UPDATE – Sergey Sigaev Oct 05 '16 at 15:34
  • I see that by default Django Rest Framework use this format of response: http://www.django-rest-framework.org/tutorial/quickstart/#testing-our-api , it's different that ExtJS expect. You need configure rootProperty at ExtJS side or on Django (I think on ExtJS side is simpler). So, for ExtJS just add props for reader in store's proxy like this: `reader: { type: 'json', rootProperty: 'results', totalProperty: 'count' }` Perhaps you will need configure success property of reader, but I not sure from where you will take success field. – Selmaril Oct 06 '16 at 02:11
  • I do this. Launch Django server using Pycharm. Then I run the page with the ExtJS JavaScript code in WebStorm using Chrome web browser. In console i see this error: `XMLHttpRequest cannot load http://127.0.0.1:8000/products/?_dc=1475751708571&page=1&start=0&limit=25. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.` I do not know how to fix it. Could you help me figure it out? – Sergey Sigaev Oct 06 '16 at 11:03
  • Your web page try to get data from another domain (http://localhost:63342 from http://127.0.0.1:8000/). It's named cross-domain request, and it is not safe operation. Browsers and web servers forbid this by default, but you can set special HTTP headers to allow it. You can read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS http://enable-cors.org/ Here ExtJS example: http://stackoverflow.com/questions/29901581/cors-issue-when-requesting-from-extjs-to-node-js-request-or-response-header-inc – Selmaril Oct 06 '16 at 11:37
  • But I think it's happens because you use Sencha CMD as web server for UI and Django on another web server for data. If it's not planned, will be better use only Django's web server, and host there ExtJS web pages. Sencha CMD better use just for compilation of web application. – Selmaril Oct 06 '16 at 11:41
  • Do I understand correctly that I have to add ExtJS code to Django project to solve this problem? – Sergey Sigaev Oct 06 '16 at 13:51
  • Yes, exactly. It is most easy way, I think. – Selmaril Oct 06 '16 at 14:50
  • Оказывается Вы из Москвы. Спасибо большое за помощь. Все получилось :) – Sergey Sigaev Oct 07 '16 at 14:34