-1

I am creating certain model's object picker which is activated when user sends a post request via HTML forms. More specifically once user clicks certain submit button and post request is sent to the website, It then returns variable which is then used by javascript to open a status window.

Here is all the code associated with these actions:

HTML

<form id="item_selection1" action="{% url 'Home:AccountPage' %}" method="post">
    {% csrf_token %}
    <input class="sendtrade" name="sendtrade1" type="submit" value="Send Offer">
</form>

Python - views.py (3 dots represent all unassociated code)

...
prepareTrade1 = "false"
...
if request.POST.get('sendtrade1'):
    prepareTrade1 = "true"
    ...
return render(request, 'Home/name.html', {"...": "...", 'prepareTrade1': prepareTrade1})

Javascript in HTML

if ( "{{ prepareTrade1 }}" == "true" ) {
    $(".process_overlay").css("display", "block")
}

Shortly, when user clicks the submit button box appears, What i'm trying to do, Is to display status of object query.

So for example, If i received ObjectDoesNotExist error from test.py which belongs in the same directory as views.py, How could i direct that information to HTML/Javascript user is receiving? If creation of absolute new request is required, Then still, How could i do that? Am i required to use Ajax requests?

So in short, Asynchronously when template name.html is rendered, The script name.py which belongs in the same directory as views.py should be executed, And lets take the example that ObjectDoesNotExist exception will be raised in name.py How could i pass it to template? I think the process is called XHR.

ShellRox
  • 2,532
  • 6
  • 42
  • 90
  • Are you using Ajax requests or you are renderings the template and js in it – Arpit Solanki Jun 27 '17 at 18:09
  • @ArpitSolanki No i am just rendering templates as seen in the code, Are ajax requests necessary in this case? – ShellRox Jun 27 '17 at 18:12
  • Just remove the quotes from "{{ prepareTrade1 }}" and you are good. It would work. – Arpit Solanki Jun 27 '17 at 18:13
  • @ArpitSolanki The following code is fully functional, Even in quotes, What i'm trying to do is make live action template rendering, So for example, Once template `name.html` is visible to user, Script `test.py` is executed and it should direct it's status as variable to `name.html` to that user, Could that be possible? – ShellRox Jun 27 '17 at 18:18
  • Use Ajax requests in js and send a json response from your Django view – Arpit Solanki Jun 27 '17 at 18:19
  • @ArpitSolanki Thanks for the answer, Could you give more information like how could i do this with ajax requests? Thanks in advance. – ShellRox Jun 27 '17 at 18:21

2 Answers2

1

Make a separate function to check for the value prepareTrade1 and this function will be used by your frontend side to show the window. csrf exempt is used just for simplicity of example

@csrf_exempt 
def check_trade(request):
    if request.POST.get('sendtrade1'):
        prepareTrade1 = "true"
        return HttpResponse(json.dumps({"prepareTrade": "true"}))
    else:
        return HttpResponse(json.dumps({"prepareTrade": "false"}))

Now the ajax request using jquery

    $.ajax({
        dataType: 'json',
        type: "POST",
        url: URL,
        data: {"sendtrade1": "somevalue"},
        success: function (response) {
          response = JSON.parse(response)
          // now time for the logic you mentioned
          if ( response.prepareTrade == "true" ) {
               $(".process_overlay").css("display", "block")
          }
        }
    });

Some links that might help you:

https://stackoverflow.com/a/13465764/5250746

Ajax tutorial for post and get

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
  • So i should just add my script to views.py as a request function? And then how could i send this data to other request which shows the user information? – ShellRox Jun 27 '17 at 18:40
  • The jQuery code will go to your script tag in your html template and check_trade function will go to views.py – Arpit Solanki Jun 27 '17 at 18:42
  • Sorry i'm not experienced in Ajax so i don't quite understand, So if i use this code, If user submits the button both request function and my script should be executed right? And then if i receive ObjectDoesNotExist exception how could i show it on request view? – ShellRox Jun 27 '17 at 18:48
  • The example only explains how to make Ajax requests. If you want to attach a handler like listener to button click or submit button then you can use $('#idofsubmitbutton').on('click', function ()). Then write your Ajax logic in the function provided in the callback – Arpit Solanki Jun 27 '17 at 18:52
  • Also see the other answer for more clarifications – Arpit Solanki Jun 27 '17 at 18:53
  • Yes, But once script is executed (and script doesn't belong in views.py), How can i pass variables between it and ajax request? – ShellRox Jun 27 '17 at 18:55
  • Your js is always available in the html file and it will be executed everytime someone submits the form(the other answer) and views code will be executed everytime you make the Ajax request – Arpit Solanki Jun 27 '17 at 18:58
  • Yes but also asynchronously with request being rendered, script called `name.py` should be executed, And can i use ajax request inside that `name.py` script ? – ShellRox Jun 27 '17 at 19:00
  • There is one simple concept. There is your server running where your views will receive requests. Ajax request will make request to the URL and Django will return the response. That's all other than that nothing is related between your js and Django. Also you can't use a js code inside name.py. – Arpit Solanki Jun 27 '17 at 19:06
  • So i still couldn't pass variables between `name.py` and `name.html` template in a "live action"? Apologies, I'm not quite sure what is this process called. – ShellRox Jun 27 '17 at 19:09
  • I am sorry to say this but you are really having hard time grasping this concept. You have to read about js Ajax and how client server works. – Arpit Solanki Jun 27 '17 at 19:11
  • The concept itself seems quite difficult, But may i ask if this could be done with ajax? Passing variables between `name.py` and `name.html` in a live action? I'm not even sure if this can be done at all... – ShellRox Jun 27 '17 at 19:13
1

You should use ajax requests to update variables from server.

Here goes you form

<form id="item_selection1" action="{% url 'Home:AccountPage' %}" method="post">
  {% csrf_token %}
  <input class="sendtrade" name="sendtrade1" type="submit" value="Send Offer">
</form>

You should rewrite you view to support ajax requests:

import json
from django.http import HttpResponse

def your_view(request):    
    ...
    prepareTrade1 = "false"
    ...
    if request.POST.get('sendtrade1'):
        prepareTrade1 = "true"
        return HttpResponse(json.dumps({'prepareTrade1': prepareTrade1}))
    else:
        return HttpResponse(json.dumps({'prepareTrade1': 'false'}))

And add following javascript:

$(function() {
  var form = $('#item_selection1');

  $(form).submit(function(event) {

    event.preventDefault();

    var formData = $(form).serialize();

    $.ajax({
      type: 'POST',
      url: $(form).attr('action'),
      data: formData,
      dataType: 'json',
      success: function(response) {
        if (response.prepareTrade1 == "true") {
          $(".process_overlay").css("display", "block");
        }
      }
    })
  });
});
Igor Yudin
  • 393
  • 4
  • 10
  • Hello, Thanks for the answer, But for example i have script `name.py`, which will be executed when button is clicked, And for example i get exception from the script and request is already loaded, How can i update that request with following exception? – ShellRox Jun 27 '17 at 18:55
  • 1
    Do you want to pass exception message to client-side? This way you should simply pass two variables in json-response: status and message. And depends on status success function will either show block or exception message. – Igor Yudin Jun 27 '17 at 19:44
  • But for example, If i executed script from different process, Could i pass exception message to client side? For example i wanted to use time.sleep function on script which would give exception result. – ShellRox Jun 27 '17 at 19:49
  • You mean that it's called another view on button click, not that renderes a template? Or you call the same view on button click, but in this view another function is called? – Igor Yudin Jun 27 '17 at 19:59
  • I mean when button is clicked, same view is called, But yes, in this view another function is called which must always work and if it gets updated it must send information to rendered HTML. So HTML must be rendered along with script, Even if script is not yet finished. I think it is called XHR. – ShellRox Jun 27 '17 at 20:12
  • 1
    In this way, you can do two things. First, in you view you could call the function with parallel execution and set limit for time waiting, and returns answer depends on the fact did the function end (success message) or not (exception message). You can also set timeout limit to ajax function without changing you server-side architecture. This way ajax must have two callbacks for success and error. Is it what you need? – Igor Yudin Jun 27 '17 at 20:26
  • Yes, Couldn't this also be done without Ajax? For example if i created another thread for script and rendered HTML, Then transferred information with websockets? – ShellRox Jun 27 '17 at 20:29
  • 1
    If you don't use ajax, you page will be reloaded each time. Using ajax is the most simple way to achive what you want. You can do parallel execution on server-side to get exception message but you shouldn't transfer information in any other way. That's very unsafe. – Igor Yudin Jun 27 '17 at 20:35
  • 1
    You could also use interecooler lib which make ajax quite simple. Look [this example](https://www.petercuret.com/add-ajax-to-django-without-writing-javascript/) – Igor Yudin Jun 27 '17 at 20:43
  • Thanks a lot! My question was fully answered now, I will just learn more about Ajax and use it for good. – ShellRox Jun 27 '17 at 21:42