2 years ago

#68240

test-img

Denis

Output the Json Response dictionary to the django template

I'm just starting to learn django. Please tell me how I can better implement my idea. JsonResponse sends a response to a separate url (url_to_django/load_table/), how do I output this dictionary to group.html?

Html

<tbody id="table_person_id">
        {% if pers %}
        {% for pers in persons_list %}
        <tr>
            <th scope="row"><div><input class="form-check-input" type="checkbox" id="checkboxNoLabel1" value="" aria-label="..."></div></th>
            <th scope="row">{{forloop.counter}}</th>
            <th scope="col">{{persons_list.Id_Group}}</th>
            <th scope="col">{{persons_list.get_Type_Participation_display}}</th>
            <th scope="col">{{persons_list.display_id_people}}</th>
            <th scope="col">{{persons_list.Competencies}}</th>
            <td>
                <button value="{{person.Id_Group}}" onclick="delete_person(this.value)">delete</button>
            </td>
        </tr>
        {% endfor %}
        {% endif %}
</tbody>

<script>
    function loadTable() {
        let xhttpTableGrops = new XMLHttpRequest()
        xhttpTableGrops.onreadystatechange = function (data) {
            if (this.readyState === 4 && this.status === 200) {
                document.getElementById("table_person_id").innerHTML = this.response
            }
        }
        xhttpTableGrops.open("GET", "/main/url_to_django/load_table/", true)
        xhttpTableGrops.send()
    }
 </script>

Urls.py

urlpatterns = [
path('', views.start, name="start"),
path('group', views.Groups.as_view(), name='group'),

path(
    'url_to_django/load_table/',
    views.load_table,
    name='load_table')

Views.py

def load_table(request):

    if request.method == "GET":
        if request.user:
            try:
            persons = AkpGroup.objects.filter(Id_Incidents=120)  # запрос в базу данных
            except AkpGroup.objects.DoesNotExist:
                persons = None

            pers = persons.all().values()
            persons_list = list(pers)
            return JsonResponse(persons_list, safe=False)
        else:
            return HttpResponse(status=403)
    else:
        return HttpResponse(status=405)

python

json

django

ajax

django-urls

0 Answers

Your Answer

Accepted video resources