Search code examples
ajaxdjangoauthenticationextjs4

Login form ExtJS 4 Ext.Ajax.request Server Django 1.5


I work with ExtJs 4.2.1, Django 1.5.2, DB Postgresql 9.1.

I have a login form in my web site, which is shown after the user clicks on a button in a toolbar. After he/she inserts the credentials (username and password) and clicks on the Submit button, this information is sent to server.

On the server side a view.py script is called, in particular one method for login (def request_login(request)), where some checks for login and user authentication are done. After these controls an httpResponse with text "success" or "error" is sent to the client. Unfortunately the client doesn't receive any message, but instead the index.html page. I tried to change type of exchange's message with json, but the result is the same...no error/success message, instead the index.html page is returned.

I saw the Django's doc that explains a general situation: client with classical form (index.html) -> click on submit and send a message with method POST -> there is a view.py with some method that receives this informations -> server send the response with message. In generally there is a redirect in the same page if login is wrong or another page if login is succeffully. In my case I want that the login return in the same page (index.html).

Login form code:

var winLogin;

Ext.onReady(function(){
    Ext.tip.QuickTipManager.init(); //init tooltip

    //create a panel to login
    var loginFormPanel = Ext.create('Ext.form.Panel', {
        bodyPadding: 15,
        defaults: { //applying default settings to all added items
            anchor: '100%',
            xtype: 'textfield',
            vtype: 'alphanum',
            allowBlank: false,
        },
        fieldDefaults: {
            labelWidth: 80,
            labelAlign: 'left',
            msgTarget: 'side',
        },
        items: [{
                name: 'username',
                fieldLabel: 'User Name',
                minLength: 3,
                maxLength: 20,
            },{
                name: 'password',
                fieldLabel: 'Password',
                inputType: 'password',
                minLength: 4,
                maxLength: 16,
            },
        ],
        dockedItems: [
            {
                xtype: 'toolbar',
                dock: 'bottom',
                items: [
                    { xtype: 'tbfill' },
                    {
                        xtype: 'button',
                        itemId: 'cancel',
                        text: 'Cancel',
                        listeners: {
                            click: function() {
                                this.up('form').getForm().reset(); //reset all textfiled
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        itemId: 'submit',
                        formBind: true,
                        text: "Submit",
                        listeners: {
                            click: function() {
                                var formPanel = this.up('form');
                                var user = formPanel.down('textfield[name=username]').getValue();
                                var pass = formPanel.down('textfield[name=password]').getValue();
                                if (formPanel.getForm().isValid()) {
                                    Ext.Ajax.request({
                                        url: 'editor/request_login',// call method in the django's view
                                        method: 'POST',
                                        params: {
                                            username: user,
                                            password: pass,
                                        },
                                        success: function (response, opts) {
                                            var text = response.responseText;
                                            Ext.Msg.alert('Success', text);
                                        },
                                        failure: function (response, opts) {
                                            var text = response.responseText;
                                            Ext.Msg.alert('Failure', text);
                                        },
                                    });
                                }
                            }
                        }
                    }
                ]
            }
        ]
    });

    //create window to contain panel
    winLogin = Ext.create('Ext.window.Window', {
        title: 'Login',
        closeAction: 'hide',
        height: 170,
        width: 360,
        layout: 'fit',
        iconCls: 'imgToolBarButtonLogin',
        resizable: false,
        draggable: false,
        modal: true,
        items: [
            loginFormPanel,
        ],
    });
    winLogin.center();
});

view.py (server):

# Create your views here.
from django.contrib.auth import authenticate, login
from django.http import HttpResponse

def request_login(request):
    if request.method == 'POST':
        requser = request.POST['username']
        reqpass = request.POST['password']
        user = authenticate(username=requser, password=reqpass)
        if user is not None:
            if user.is_active:
                login(request, user)
                # Return a success message
                return HttpResponse("Success", content_type="text/plain")
            else:
                # Return a 'disabled account' error message
                return HttpResponse("Error: this account is disabled!", content_type="text/plain")
        else:
            # Return an 'invalid login' error message.
            return HttpResponse("Error: invalid login. Try again!", content_type="text/plain")

Login (modified with JSON):

...
                    {
                        xtype: 'button',
                        itemId: 'submit',
                        formBind: true,
                        text: "Submit",
                        listeners: {
                            click: function() {
                                var formPanel = this.up('form');
                                var user = formPanel.down('textfield[name=username]').getValue();
                                var pass = formPanel.down('textfield[name=password]').getValue();
                                if (formPanel.getForm().isValid()) {
                                    Ext.Ajax.request({
                                        url: 'editor/request_login',// call method in the django's view
                                        method: 'POST',
                                        params: {
                                            username: user,
                                            password: pass,
                                        },
                                        success: function (response, opts) {
                                            var json = Ext.JSON.decode(response.responseText);
                                            Ext.Msg.alert('Success', json['message']);
                                        },
                                        failure: function (response, opts) {
                                            var json = Ext.JSON.decode(response.responseText);
                                            Ext.Msg.alert('Failure', json['message']);
                                        },
                                    });
                                }
                            }
                        }
                    }
...

View.py (modified with JSON):

# Create your views here.
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
import json

def request_login(request):
    if request.method == 'POST':
        requser = request.POST['username']
        reqpass = request.POST['password']
        user = authenticate(username=requser, password=reqpass)
        response_data = {}
        if user is not None:
            if user.is_active:
                login(request, user)
                # Return a success message
                response_data['result'] = 'success'
                response_data['message'] = 'Has loged in'
                response_data['fullname'] = user.get_full_name()
                return HttpResponse(json.dumps(response_data), content_type="application/json")
            else:
                # Return a 'disabled account' error message
                response_data['result'] = 'disabled'
                response_data['message'] = 'this user is disabled'
                return HttpResponse(json.dumps(response_data), content_type="application/json")
        else:
            # Return an 'invalid login' error message.
            response_data['result'] = 'failed'
            response_data['message'] = 'invalid login'
            return HttpResponse(json.dumps(response_data), content_type="application/json")

Solution

  • Ok, I found the error! The path in url option was wrong.

    Thanks