Динамическая загрузка данных в шаблон Django из Django Modal без обновления страницы

У меня есть следующая модель Django, и я использую первые 3 поля для создания древовидного представления в шаблоне, как показано ниже.

class operationTemplates(models.Model):
    templateID = models.IntegerField(primary_key = True)
    templateCategory = models.CharField(max_length=255, blank=True, null=True)
    templateName = models.CharField(max_length=400, blank=True, null=True)
    templatePreopBundle = models.TextField( blank=True, null=True)
    templateIndication = models.TextField( blank=True, null=True)
    templatePosition = models.TextField( blank=True, null=True)
    templateProcedure = models.TextField( blank=True, null=True)
    templateClosure = models.TextField( blank=True, null=True)
    templatePostOpInstructions = models.TextField( blank=True, null=True)

                                <!-- tree view -->
                                <ul class="tree">
                                    <li>
                                        <input type="checkbox" id="c0" />
                                        <label class="tree_label" for="c0">Vascular Surgery</label>
                                        <ul>
                                            {% for k, v in group.items %}
                                            <li>
                                              <input type="checkbox"  id="c{{forloop.counter}}" />
                                              <label for="c{{forloop.counter}}" class="tree_label">{{ k }}</label>
                                              <ul>
                                                  {% for x in v %}
                                                    <li><span class="tree_label"><a href="{{ x.templateID }}">{{ x.templateName }}</a></span></li>
                                                  {% endfor %}
                                              </ul>
                                            </li>
                                            {% endfor %}
                                        </ul>
                                    </li>
                                </ul>
                                <!-- tree view end-->

Деревовидное представление, сгенерированное динамически с использованием даты из вышеуказанного модала

Когда пользователь щелкает на определенном листе дерева, я хочу иметь возможность запрашивать и отображать все поля, относящиеся к этой записи, из модели Danjo без обновления страницы.

Каким способом лучше всего этого добиться? Нужно ли мне использовать JSON/JavaScript? Или есть элегантный способ сделать это просто с помощью Django и HTML?

Заранее спасибо

Вы можете использовать ajax. В вашем шаблоне напишите код ajax. В представлении выведите json из вашего объекта. Если вам нужен пример, дайте мне знать, это не очень сложно сделать.

Я преобразовал листья дерева в кнопки и использовал AJAX для динамического запроса к модели Django.

шаблон

Я хочу заполнить эту текстовую область;

<form class="addOperationForm" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                        <table width="100%">
                           
                            <tr>
                                <td colspan="2">
                                    <textarea id="opnoteTextArea" name='opnoteTextArea' placeholder='Edit your opnote here!' rows="25"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <br>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <input class="ner-btn" type="reset" value="Reset">
                                    <button class="ner-btn" id="addOperationNote" type="submit">AddNote</button>
                                    <button class="ner-btn" id="opnoteNER" type="submit">OpnoteNER</button>
                                </td>
                            </tr>
                        </table>
                    </form>

когда вы нажимаете на эти кнопки;

{% for x in v %}
<button id="tree_label" value="{{ x.templateID }}">{{ x.templateName }}</button>
{% endfor %}

Я использую следующий javascript для захвата события щелчка

Сценарий

$("button").click(function() {
        //get the templateID
        var templateID = $(this).val();

        // GET AJAX request
        $.ajax({
            type: 'GET',
            url: "{% url 'loadSelectedTemplate' %}",
            data: {"templateID": templateID},
            success: function (response) {

                // display the template loaded from AJAX
                var instance = JSON.parse(response["template"]);
                var fields = instance[0]["fields"];
                console.log(fields);

            },
            error: function (response) {
                console.log(response)
            }
        })
    });

views.py

def loadSelectedTemplate(request):
    # request should be ajax and method should be GET.
    if request.is_ajax and request.method == "GET":
        # get the template matching the ID
        templateID = request.GET.get("templateID", None)
        # check for the template matching ID in the database.
        template = operationTemplates.objects.filter(templateID = templateID)
        if template:
            # if template found return record
            ser_template = serializers.serialize('json', [ template, ])
            return JsonResponse({"template": ser_template}, status = 200)
        else:
            # if nick_name not found, then user can create a new friend.
            return JsonResponse({"template":False}, status = 200)

    return JsonResponse({}, status = 400)

Но я все еще не могу понять, как заполнить текстовую область, используя ответ JSON.

Пробовали разные методы, но ни один не сработал;

document.getElementById("opnoteTextArea").value += fields;
 

Добавьте ваш ответ в ваш div

$("button").click(function() {
    //get the templateID
    var templateID = $(this).val();

    // GET AJAX request
    $.ajax({
        type: 'GET',
        url: "{% url 'loadSelectedTemplate' %}",
        data: {"templateID": templateID},
        success: function (response) {

            // display the template loaded from AJAX
            var instance = JSON.parse(response["template"]);
            var fields = instance[0]["fields"];
            console.log(fields);
           ===>$("#opnoteTextArea")opnoteTextArea.append(fields)
           

        },
        error: function (response) {
            console.log(response)
        }
    })
});
Вернуться на верх