Multiple post requests in django

I am new to Django and working on a small web application, in which one of the part is to list down the available documents based on the project selected and when the list is displayed in the table, user can selected one from the list and click on Next button. When Next is clicked it should update the Select as True and Locked by User as current user and then move to next tab.

The Search shown in the screenshot is working fine and i am getting the details but the issue is with the Next button, it is not updating anything and simply moving to the next tab. This Next tab functionality is being handled in Javascript.

Below is my code:

Template form.html:

<form method="POST">
                            {% csrf_token %}
                            <div class="row ml-auto">
                                <select class="custom-select mb-4 ml-2" name="selectproject" style="width: 30em;">
                                    <option selected>Choose...</option>
                                    {% for projects in projects %}
                                    <option>{{ projects.ProjName}}</option>
                                    {% endfor %}
                                </select>
                                <div class="ml-4">
                                    <button type="submit" class="btn btn-primary" value="Search">Search</button>
                                </div>
                            </div>
                            
                            <table class="table">
                                <thead class="thead-light">
                                    <tr>
                                        <th scope="col" class="text-center">S.No.</th>
                                        <th scope="col" class="text-center">Project Name</th>
                                        <th scope="col" class="text-center">Doc</th>
                                        <th scope="col" class="text-center">Target Date</th>
                                        <th scope="col" class="text-center">Docnum</th>
                                        <th scope="col" class="text-center">Type</th>
                                        <th scope="col" class="text-center">Select</th>
                                        <th scope="col" class="text-center">Locked by User</th>
                                        <th scope="col" class="text-center">Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for lists in lists %}
                                    <tr>
                                        <th scope="row" class="text-center">{{ lists.id }}</th>
                                        <td class="text-center">{{ lists.Project }}</td>
                                        <td class="text-center">{{ lists.doc }}</td>
                                        <td class="text-center">{{ lists.TargetDate }}</td>
                                        <td class="text-center">{{ lists.docnum }}</td>
                                        <td class="text-center">{{ lists.type }}</td>
                                        <td class="text-center"><input class="form-check-input" type="radio"
                                                name="select1" id="selectradio" value="option1"></td>
                                        <td class="text-center">{{ lists.LockedUser }}</td>
                                        <td class="text-center">
                                            {% if lists.DStatus == "Available" %}
                                            <label class="badge badge-success">
                                                {% else %}
                                                <label class="badge badge-warning">
                                                    {% endif %}
                                                    {{ lists.DStatus }}</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                            <div class="text-right mr-5">
                                <button type="submit" class="btn btn-primary" id="nexttab" name="tab1btn"
                                    value="nxttab">Next</button>
                            </div>

                        </form>

JavaScript:

    $('#nexttab').click(function(e){
        e.preventDefault();
        if(document.getElementById('selectradio').checked){
              $('#tabs a[href="#tab2"]').tab('show');
        }
    });
})

View:

    projects = CreateProjects.objects.filter(Status=True)
    if request.method == 'POST':
        selectproject = request.POST.get('selectproject')
        searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
        return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
    elif request.POST.get('tab1btn','') == 'nxttab':
        selval = ListProjDetails.objects.get(id=1)
        selval.Selected = True
        selval.LockedUser = request.user
        selval.save()
    else:
        lists = ListProjDetails.objects.all()
        return render(request,'form.html',{'projects':projects})

I tried to explain the issue, please let me know if any more information is needed

Your nexttab JavaScript function isn’t doing anything to call the view on the server to have it update your data. You need to add some form of AJAX call to pass data to the server.

(Also, I wouldn’t structure it for your JS to invoke the same view. I’d set up a separate view for the JS to call, returning the data you can use to update your page without refreshing the entire page.)

Thank you for the suggestion!
I have made the changes now to use AJAX call inorder to achieve my requirement. But just one more thing which is not working now. If you can suggest a way that would be great!!

How can i pass the id from HTML (below mentioned table) back to Django view when the option is selected from the result.

{% for lists in lists %}
     <tr>
          <th scope="row" class="text-center">{{ lists.id }}</th>
          <td class="text-center">{{ lists.Project }}</td>
          <td class="text-center">{{ lists.doc }}</td>
          <td class="text-center">{{ lists.TargetDate }}</td>
          <td class="text-center">{{ lists.docnum }}</td>
         <td class="text-center">{{ lists.type }}</td>
         <td class="text-center"><input class="form-check-input" type="radio"                      
             name="select1" id="selectradio" value="option1"></td>
         <td class="text-center">{{ lists.LockedUser }}</td>
     </tr>
{% endfor %}

Pass the id from the HTML to below view

selval = ListProjDetails.objects.get(id=<pass id the value here>)

The value attribute is what you have access to in the submitted data. If you render it as value="{{ list.id }}", you would then be able to access it in your view.

Also, save yourself a lot of potential confusion and future problems - change {% for lists in lists %} to {% for list in lists %} and your references to list within the loop as well.
Actually, since list is a keyword, that’s probably not the best choice either. I’d probably use a_list to be explicit that I’m referencing one entity from the set of lists.

Thanks again for the quick response!!

Actually I have tried value ={{slist.id}} (changed that lists to slist) before but the problem I faced with this one is, if there are multiple rows for each project it always return id as 1, even if I select the 2nd row in the table.

Do you also have the same id value across all entries? (You should never have two elements on the same page with the same ID.)
The set of radio buttons within a group is identified by the same name but the id should be different.
Don’t know if that would cause this particular behavior or not. (If you’re using JS w/AJAX to find / submit this data then it would be the issue, because a get-element-by-id is going to find the first one.)

I think there is some fault in my Django view or ajax call, but i am not able to figure out. I am new to django and still learning from the mistakes. Can you please help?

I am trying to pass the id value of the selected option to Django view through Ajax and then on success to ajax, move to next tab action to be performed, but i am facing 2 issues here (based on 2 different code blocks i tried):

If i use this code block:

#form-post is the name of the form

$(document).on(submit,'#form-post', function(e){
     e.preventDefault();
    $.ajax({
        type:'POST',
        url:'/form',
        data:{
            Selected:$('#selectradio').val(),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        },
        success:function(json){
                alert('in success');
                $('#tabs a[href="#tab2"]').tab('show');
        },
        error : function(xhr,errmsg,err) {
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
    }
    });
});

I am getting the below output: and not moving to the next tab as it is not going into success:function but the correct id value is being passed, hence i am getting the below:

{"Selected": true, "LockedUser": "user1"}

If i am using the below: , it is going into the success:function and moving to the next tab but the selected value being passed is wrong (always same value, like ex., if there are 3 rows, out of that if i select 2nd row i would expect 2 as value but i am getting 1 . In the above code i am getting 2 but not moving to next tab instead getting json response .

Here #nexttab is the button that when clicked/submitted it has to perform the move next tab action after performing the save in the django view

$('#nexttab').on('click', function(e){
     e.preventDefault();
    $.ajax({
        type:'POST',
        url:'/form',
        data:{
            Selected:$('#selectradio').val(),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        },
        success:function(json){
                alert('in success');
                $('#tabs a[href="#tab2"]').tab('show');
        },
        error : function(xhr,errmsg,err) {
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
    }
    });
});

My View:

def form(request):
    projects = CreateProjects.objects.filter(Status=True)
    response_data = {}
    if request.method == 'POST':
        if 'selectproject' in request.POST and request.POST.get('batch','') == 'Search':
            selectproject = request.POST.get('selectproject')
            searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
            return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
        if 'Selected' in request.POST:
            print('ID is: ', request.POST.get('Selected'))
            selval = ListProjDetails.objects.get(id=request.POST.get('Selected'))
            # selval.Selected = True
            selval.LockedUser = str(request.user)
            selval.Status = 'Allocated'
            response_data['Selected'] = True
            response_data['LockedUser'] = str(request.user)
            selval.save()  
            return HttpResponse(json.dumps(response_data), content_type="application/json")
    else:
        return render(request,'form.html',{'projects':projects}) 

You’re searching for an html id attribute named “selectradio”. That is wrong. Do not create multiple entities with the same id.
What you want to do is retrieve the value based upon the ‘name’ attribute, and if you need to assign an id to each button (generally not needed), then make sure that it is different for each button.

If you google jquery radio button value, you’ll find plenty of examples.

1 Like

Thanks a lot… that worked :slight_smile: