admin管理员组

文章数量:1023116

I want to put loading image while saving data in database. So ,I Ajax call to do it. I use Django 1.8 and after put Ajax call Django not redirect default page after adding data successfully.I check data in save successfully and view.py method also run.

Before put Ajax call when I submit invalid data to forum and when submit it ,show validation errors.but now only view Ajax error message.

but after add ajax , now I enter submit without data didn't show above instruction(validation error). I used Django default validation an they are defined model class when create form.

----------------keylist.html------------------------------

{ % extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}
  {% if create %}Create{% else %}New Key{% endif %}Serious
{% endblock %}

{% block heading %}
  <h2>
      Create New Serial Keys
  </h2>
{% endblock %}

{% block content %}
  {% if create %}
    {% url "marcador_key_create" as action_url %}
  {% else %}
    {% url "marcador_bookmark_search" pk=form.instance.pk as action_url %}
  {% endif %}
  <form action="{{ action_url }}" method="post" accept-charset="utf-8" id="createForm" >
    {{ form|crispy }}
    {% csrf_token %}
    <div id="submit_loader"></div>
    <p> <b>Expiry Date*:</b>  <input type="date" id="datepicker" name="expier_date"></p>
    <p><input type="submit" class="btn btn-default" value="Save"   id="save_button"> </p>

  </form>

{% endblock %}

-------base.html (ajax method )-------------------------------------

   <script>
       // Attach a submit handler to the form
       $("#createForm").submit(function (event) {
             event.preventDefault();

             //var formData = new FormData($("#createForm")[0]);
             var serverUrl =$("#createForm").attr('action');

             $.ajax({
                        url: serverUrl,
                        type: 'POST',
                        data: $("#createForm").serialize(),

                        beforeSend: function() {
                              $('#submit_loader').css('display','block');
                        },
                       plete: function(){
                              $('#submit_loader').css('display','none');
                       },
                       success: function (returndata) {
                            alert("succsesfully generate keys");
                            //window.location("xsd");
                            //return false;
                       },
                       error: function(data){
                           alert("please ,check you fill form correctly");
                       }
               });
               //return false;
       });
</script>

---------view.py (calling method )----------------------------------

   @login_required
def key_create(request):
    #print(request.POST)

    if request.method == 'POST':
        form = KeyGenarateForm(data=request.POST)
        expier_date = request.POST['expier_date']
        #print(expier_date=="")
        if(expier_date==""):
            form.is_valid= False;


        if form.is_valid():
             #request.POST._mutable = True
             Key_Gen = form.save(mit=False)
             Key_Gen.save(expier_date)
             return redirect('marcador_bookmark_user',username=request.user.username)
        else:
            print('form not valied')
            return render('marcador_bookmark_user',username=request.user.username)
    else:
        form = KeyGenarateForm()

    context = {'form': form, 'create_key': True}
    return render(request, 'marcador/key_genarate_form.html', context)

I test when I enter valid data and submit , every thing successfully , but didn’t redirect my url.It show my old data in the field.

As,I noticed view.py return method not loading.

  return redirect('marcador_bookmark_user',username=request.user.username)

not execute.

please , expect some expert help.

I want to put loading image while saving data in database. So ,I Ajax call to do it. I use Django 1.8 and after put Ajax call Django not redirect default page after adding data successfully.I check data in save successfully and view.py method also run.

Before put Ajax call when I submit invalid data to forum and when submit it ,show validation errors.but now only view Ajax error message.

but after add ajax , now I enter submit without data didn't show above instruction(validation error). I used Django default validation an they are defined model class when create form.

----------------keylist.html------------------------------

{ % extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}
  {% if create %}Create{% else %}New Key{% endif %}Serious
{% endblock %}

{% block heading %}
  <h2>
      Create New Serial Keys
  </h2>
{% endblock %}

{% block content %}
  {% if create %}
    {% url "marcador_key_create" as action_url %}
  {% else %}
    {% url "marcador_bookmark_search" pk=form.instance.pk as action_url %}
  {% endif %}
  <form action="{{ action_url }}" method="post" accept-charset="utf-8" id="createForm" >
    {{ form|crispy }}
    {% csrf_token %}
    <div id="submit_loader"></div>
    <p> <b>Expiry Date*:</b>  <input type="date" id="datepicker" name="expier_date"></p>
    <p><input type="submit" class="btn btn-default" value="Save"   id="save_button"> </p>

  </form>

{% endblock %}

-------base.html (ajax method )-------------------------------------

   <script>
       // Attach a submit handler to the form
       $("#createForm").submit(function (event) {
             event.preventDefault();

             //var formData = new FormData($("#createForm")[0]);
             var serverUrl =$("#createForm").attr('action');

             $.ajax({
                        url: serverUrl,
                        type: 'POST',
                        data: $("#createForm").serialize(),

                        beforeSend: function() {
                              $('#submit_loader').css('display','block');
                        },
                       plete: function(){
                              $('#submit_loader').css('display','none');
                       },
                       success: function (returndata) {
                            alert("succsesfully generate keys");
                            //window.location("xsd");
                            //return false;
                       },
                       error: function(data){
                           alert("please ,check you fill form correctly");
                       }
               });
               //return false;
       });
</script>

---------view.py (calling method )----------------------------------

   @login_required
def key_create(request):
    #print(request.POST)

    if request.method == 'POST':
        form = KeyGenarateForm(data=request.POST)
        expier_date = request.POST['expier_date']
        #print(expier_date=="")
        if(expier_date==""):
            form.is_valid= False;


        if form.is_valid():
             #request.POST._mutable = True
             Key_Gen = form.save(mit=False)
             Key_Gen.save(expier_date)
             return redirect('marcador_bookmark_user',username=request.user.username)
        else:
            print('form not valied')
            return render('marcador_bookmark_user',username=request.user.username)
    else:
        form = KeyGenarateForm()

    context = {'form': form, 'create_key': True}
    return render(request, 'marcador/key_genarate_form.html', context)

I test when I enter valid data and submit , every thing successfully , but didn’t redirect my url.It show my old data in the field.

As,I noticed view.py return method not loading.

  return redirect('marcador_bookmark_user',username=request.user.username)

not execute.

please , expect some expert help.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 8, 2015 at 7:30 umauma 1,5773 gold badges32 silver badges70 bronze badges 3
  • write your redirect url in ajax success function – Saravanan N Commented Dec 8, 2015 at 7:58
  • Ajax expecting response data from server is json, xml or html, instead of redirect function – Saravanan N Commented Dec 8, 2015 at 8:11
  • @saravanann ,sir , I am new er to web developing. so , can you provide some example.it will big help to me. – uma Commented Dec 8, 2015 at 8:50
Add a ment  | 

1 Answer 1

Reset to default 4

May be this will help you:

Instead of this redirection in views.py:

return redirect('marcador_bookmark_user',username=request.user.username)

use this:

return HttpResponse(json.dumps([{username=request.user.username}]),mimetype='text/json')

At last on ajax success function:

window.location.href = '/url-path'+data.username; 

(username will be a key inside the context named "data").

I want to put loading image while saving data in database. So ,I Ajax call to do it. I use Django 1.8 and after put Ajax call Django not redirect default page after adding data successfully.I check data in save successfully and view.py method also run.

Before put Ajax call when I submit invalid data to forum and when submit it ,show validation errors.but now only view Ajax error message.

but after add ajax , now I enter submit without data didn't show above instruction(validation error). I used Django default validation an they are defined model class when create form.

----------------keylist.html------------------------------

{ % extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}
  {% if create %}Create{% else %}New Key{% endif %}Serious
{% endblock %}

{% block heading %}
  <h2>
      Create New Serial Keys
  </h2>
{% endblock %}

{% block content %}
  {% if create %}
    {% url "marcador_key_create" as action_url %}
  {% else %}
    {% url "marcador_bookmark_search" pk=form.instance.pk as action_url %}
  {% endif %}
  <form action="{{ action_url }}" method="post" accept-charset="utf-8" id="createForm" >
    {{ form|crispy }}
    {% csrf_token %}
    <div id="submit_loader"></div>
    <p> <b>Expiry Date*:</b>  <input type="date" id="datepicker" name="expier_date"></p>
    <p><input type="submit" class="btn btn-default" value="Save"   id="save_button"> </p>

  </form>

{% endblock %}

-------base.html (ajax method )-------------------------------------

   <script>
       // Attach a submit handler to the form
       $("#createForm").submit(function (event) {
             event.preventDefault();

             //var formData = new FormData($("#createForm")[0]);
             var serverUrl =$("#createForm").attr('action');

             $.ajax({
                        url: serverUrl,
                        type: 'POST',
                        data: $("#createForm").serialize(),

                        beforeSend: function() {
                              $('#submit_loader').css('display','block');
                        },
                       plete: function(){
                              $('#submit_loader').css('display','none');
                       },
                       success: function (returndata) {
                            alert("succsesfully generate keys");
                            //window.location("xsd");
                            //return false;
                       },
                       error: function(data){
                           alert("please ,check you fill form correctly");
                       }
               });
               //return false;
       });
</script>

---------view.py (calling method )----------------------------------

   @login_required
def key_create(request):
    #print(request.POST)

    if request.method == 'POST':
        form = KeyGenarateForm(data=request.POST)
        expier_date = request.POST['expier_date']
        #print(expier_date=="")
        if(expier_date==""):
            form.is_valid= False;


        if form.is_valid():
             #request.POST._mutable = True
             Key_Gen = form.save(mit=False)
             Key_Gen.save(expier_date)
             return redirect('marcador_bookmark_user',username=request.user.username)
        else:
            print('form not valied')
            return render('marcador_bookmark_user',username=request.user.username)
    else:
        form = KeyGenarateForm()

    context = {'form': form, 'create_key': True}
    return render(request, 'marcador/key_genarate_form.html', context)

I test when I enter valid data and submit , every thing successfully , but didn’t redirect my url.It show my old data in the field.

As,I noticed view.py return method not loading.

  return redirect('marcador_bookmark_user',username=request.user.username)

not execute.

please , expect some expert help.

I want to put loading image while saving data in database. So ,I Ajax call to do it. I use Django 1.8 and after put Ajax call Django not redirect default page after adding data successfully.I check data in save successfully and view.py method also run.

Before put Ajax call when I submit invalid data to forum and when submit it ,show validation errors.but now only view Ajax error message.

but after add ajax , now I enter submit without data didn't show above instruction(validation error). I used Django default validation an they are defined model class when create form.

----------------keylist.html------------------------------

{ % extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}
  {% if create %}Create{% else %}New Key{% endif %}Serious
{% endblock %}

{% block heading %}
  <h2>
      Create New Serial Keys
  </h2>
{% endblock %}

{% block content %}
  {% if create %}
    {% url "marcador_key_create" as action_url %}
  {% else %}
    {% url "marcador_bookmark_search" pk=form.instance.pk as action_url %}
  {% endif %}
  <form action="{{ action_url }}" method="post" accept-charset="utf-8" id="createForm" >
    {{ form|crispy }}
    {% csrf_token %}
    <div id="submit_loader"></div>
    <p> <b>Expiry Date*:</b>  <input type="date" id="datepicker" name="expier_date"></p>
    <p><input type="submit" class="btn btn-default" value="Save"   id="save_button"> </p>

  </form>

{% endblock %}

-------base.html (ajax method )-------------------------------------

   <script>
       // Attach a submit handler to the form
       $("#createForm").submit(function (event) {
             event.preventDefault();

             //var formData = new FormData($("#createForm")[0]);
             var serverUrl =$("#createForm").attr('action');

             $.ajax({
                        url: serverUrl,
                        type: 'POST',
                        data: $("#createForm").serialize(),

                        beforeSend: function() {
                              $('#submit_loader').css('display','block');
                        },
                       plete: function(){
                              $('#submit_loader').css('display','none');
                       },
                       success: function (returndata) {
                            alert("succsesfully generate keys");
                            //window.location("xsd");
                            //return false;
                       },
                       error: function(data){
                           alert("please ,check you fill form correctly");
                       }
               });
               //return false;
       });
</script>

---------view.py (calling method )----------------------------------

   @login_required
def key_create(request):
    #print(request.POST)

    if request.method == 'POST':
        form = KeyGenarateForm(data=request.POST)
        expier_date = request.POST['expier_date']
        #print(expier_date=="")
        if(expier_date==""):
            form.is_valid= False;


        if form.is_valid():
             #request.POST._mutable = True
             Key_Gen = form.save(mit=False)
             Key_Gen.save(expier_date)
             return redirect('marcador_bookmark_user',username=request.user.username)
        else:
            print('form not valied')
            return render('marcador_bookmark_user',username=request.user.username)
    else:
        form = KeyGenarateForm()

    context = {'form': form, 'create_key': True}
    return render(request, 'marcador/key_genarate_form.html', context)

I test when I enter valid data and submit , every thing successfully , but didn’t redirect my url.It show my old data in the field.

As,I noticed view.py return method not loading.

  return redirect('marcador_bookmark_user',username=request.user.username)

not execute.

please , expect some expert help.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 8, 2015 at 7:30 umauma 1,5773 gold badges32 silver badges70 bronze badges 3
  • write your redirect url in ajax success function – Saravanan N Commented Dec 8, 2015 at 7:58
  • Ajax expecting response data from server is json, xml or html, instead of redirect function – Saravanan N Commented Dec 8, 2015 at 8:11
  • @saravanann ,sir , I am new er to web developing. so , can you provide some example.it will big help to me. – uma Commented Dec 8, 2015 at 8:50
Add a ment  | 

1 Answer 1

Reset to default 4

May be this will help you:

Instead of this redirection in views.py:

return redirect('marcador_bookmark_user',username=request.user.username)

use this:

return HttpResponse(json.dumps([{username=request.user.username}]),mimetype='text/json')

At last on ajax success function:

window.location.href = '/url-path'+data.username; 

(username will be a key inside the context named "data").

本文标签: javascriptAfter Ajax calldjango not redirect given urlStack Overflow