Python. Django - How to call a python function when submitting form with Ajax
Question: I have an error when loading the app which says that url in form's _action_
attribute is not correct. I've googled for several hours and tried different
variants, still no result. I'm totally new to django and would appreciate any
help. Thanks!

This is my views.py:

    
    
    from django.shortcuts import render
    from django.http import HttpResponse
    from django.template import RequestContext, loader
    from form import UserForm
    
    def index(request):
        text = "Welcome"
        template = loader.get_template('myapp/index.html')
        context = RequestContext(request, {
            'text': text,
        })
        return HttpResponse(template.render(context))
    
    
    def get_data(request):
        if request.POST:
           form = UserForm(request.POST)
           if form.is_valid():
              login = form.cleaned_data['login']
              password = form.cleaned_data['password']
    
         return render(request, 'myapp/index.html', {
                   'login': login,
                   'password': password, })
    

urls.py:

    
    
    from django.conf.urls import patterns, url
    
    from myapp import views
    
    urlpatterns = patterns('',
        url(r'^$', views.index, name='index'),
        url(r'^$/login/$', views.get_data, name='get_data'),
    )
    

index.html:

    
    
    <h1>{{ text }}</h1>
    
    <form action="{% url get_data %}" method="post" id="auth">
    {% csrf_token %}
        <p>Login:<br>
        <input type="text" name="login" id="login"> </p>
    
        <p>Password:<br>
        <input type="text" name="password" id="password"> </p>
            <input type="submit" value="Log in"">      
    </form>
    
    <div id="check"></div>
    <div>{{login}}</br>
         {{password}}
    </div>
    
    <script type="text/javascript">
        var frm = $('#auth');
    
        frm.submit(function () {
            $.ajax({
                type: frm.attr('method'),
                url: frm.attr('action'),
                data: frm.serializeArray(),
                cache: false, 
                success: function (data) {
                    $("#check").html(data); 
                },
                error: function(data) {
                    $("#check").html("Something went wrong!");
                }
            });
            return false;
        }); 
    </script>
    


Answer: The action attribute of the form should be action="{% url 'get_data' %}", not
action="{% url get_data %}".

