Home > Software engineering >  How to pass a variable coming from HTML to another django view function
How to pass a variable coming from HTML to another django view function

Time:02-26

Intro: I've been looking for all stackoverflow questions but unfortunately after hours of research I cannot find a solution that suits my needs. I have a variable generated after the user submits a form. I get this variable using an Ajax call and then I pass it to a django view.


file.html

// if user clicked submit button, call ajax to pass variable to django view 
$('#submit').click(function() {
  var dato = 0;
  $.ajax({
    url: '{% url 'todo:get_dato' %}',
    dataType: 'text',
    method: "POST",
    data: {
      csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
      data: JSON.stringify(dato),
    },
    success: function(data, status, xhr) {},
    error: function(xhr, status, error){}
  })    
});

Problem: I can "receive" this variable into a django view function but I cannot pass ajax_date variable to another view function inside the same views.py file


views.py

1st function where I get ajax variable coming from HTML

@login_required
@user_passes_test(staff_check)  
def get_dato(request):
    if request.method == 'POST' and 'data' in request.POST:
        ajax_response_dict = json.loads(request.POST['data'])
        ajax_date = ajax_response_dict.get('date_id')
        request.session['ajax_date'] = ajax_date 

2nd function where I need to use ajax_date variable

@login_required
@user_passes_test(staff_check)
def calendario(request):
    form = EventForm(request.POST)
    if form.is_valid():
        form.save()
            
        #HERE I NEED TO USE VARIABLE
        ajax_date = request.session.get('ajax_date')

Actual situation: What kind of return object should I use in get_dato() function?

If I print ajax_date from 2nd function I got:

None
<class 'NoneType'>

while inside the first function everything works:

ajax_response_dict is:

{'date_id': 0}
<class 'dict'>

ajax_date is:

0
<class 'int'>

How can I fix this issue?

CodePudding user response:

One solution is to separate your methods that render a template from those that do some sort of backend logic, for example:

views.py

def render_index(request):
    
    ''' this method serves the index.html page only '''
    
    return render(request, 'index.html')


def submit_form(request):
    
    ''' this method unpacks a post request and does something with it '''

    # unpack request:
    date = request.POST.get('date')

    # do something with date
    ...

    # create the response:
    response = {'message':'OK'}

    return JsonResponse(response)

index.html

<button id='btn'>Click Me!</button>
<script src="{% static 'scripts.js' %}"></script>

scripts.js

$('#btn').click(function() {

  /* this method sends a post request to the backend */

  $.ajax({
    url : 'submit_form',
    type : 'POST',
    data : {
      date : new Date(),
      ...
    },
    success : function(response) {

      /* this method executes on a successful response from the backend */
     
      var message = response.message
     
      // do something with the message, route user to new page, close form
      ...

    }

  });
});

CodePudding user response:

Thanks to @Daniel I found the main error into Ajax call. The problem was the line var id_data = {date_id: 0}; The js variable was empty at starting point.

BUT there was another error I made, because I was trying to print(dato) after the line if form.is_valid(): that's why I cannot get the value inside the existing view and I tried to make it work by using another view that is really useless for my goal

  • Related