Bootstrap 模式不向 django 视图发送渲染模型表单的请求

Bootstrap modal not sending a request to django view for rendering model form

提问人:leah3333 提问时间:11/7/2023 最后编辑:leah3333 更新时间:11/8/2023 访问量:35

问:

我目前正在从事一个管理生物样本库存的 django 项目。我有一个标本详细信息页面,该页面呈现了四个表,其中包含与所选标本关联的数据。在每个表中,我都有一个“编辑”按钮,用户可以在其中更新与标本关联的记录。现在,当单击该按钮时,将打开一个新页面并呈现更新表单。我想使用引导模式来创建表单的弹出窗口,而不必转到一个全新的页面。我已经在主页上创建了类似的东西来添加新的标本记录,效果很好。出于某种原因,尝试详细信息页面上的相同内容将不起作用。模式确实弹出,但表单没有呈现,似乎问题是即使指定了edit_specimen url/view,也没有向请求发送请求。我想知道这是否与 url 和 pk 在此操作的 url 中有关。我已经尝试了几件事,但我无法让它工作。任何建议都是值得赞赏的,因为我对 Django 比较陌生。

这是html

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>

这是视图

def EditSpecimenView(request,pk):
    instance = Specimen.objects.get(specimen_id=pk)
    if request.method == 'POST':
        specimen_update_form = UpdateSpecimenForm(request.POST, instance=instance)
        if specimen_update_form.is_valid:
            specimen_update_form.save()
            return redirect('home')
        else:
            specimen_update_form = UpdateSpecimenForm()
    else:
        specimen_update_form = UpdateSpecimenForm()
    context = {'spec_form': specimen_update_form}

    return render(request, 'zombie/edit_specimen.html', context)

Here are my urls
urlpatterns = [
    path('zombie/edit-specimen/(?P<pk>\w+)/', views.EditSpecimenView, name='edit_specimen'),
    path('zombie/edit-sample', views.EditSampleView, name='edit_sample'),
    path('zombie/edit-morphometrics', views.EditMorphsView, name='edit_morphometrics'),
    path('zombie/load-species/', views.get_species, name='get_species'),
    path("zombie/add-specimen/", views.AddSpecimenView, name='add_specimen'),
    path("zombie/specimen-details/(?P<pk>\w+)/", views.SpecimenDetailView, name='details'),
    path("search-results/", views.SearchResultsView, name='specimen_search_results'),
    path("home/", views.HomeTableView, name="home"),
    path("", views.index, name="index"),
]

我已经尝试了不同的建议来实现模态并从主页中获取模态并将其放入此页面,但它仍然没有呈现,这让我认为它与 url/pk 有关

编辑: 为主表/搜索页面添加 HTML 和视图。我可能需要合并到一个视图中,但稍后会进行处理。

    #home.html
        {% load django_tables2  %}
    <!DOCTYPE html>
    <html lang="es">
    <style>
        /* Center the logo horizontally */
        .center-logo {
            display: block;
            margin: 0 auto;
            text-align: center;
            padding-top: 0px;
            padding-bottom: 0px;
            transform: scale(0.8);
        }
    
        .tooltip-icon {
        font-size: 12px; /* Adjust the size of the "i" icon */
        color: coral;
        }
    
        .tooltip-icon:hover {
        font-size: 12px; /* Increase size on hover if desired */
    }
    
    </style>
    
    <head>
        <title>Specimen Table</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>
    
    <body>
        <div class="container">
            <div class="text-center">
                {% load static %}
                <img src="{% static 'zombie/logo.png' %}" alt="Your Image" class="center-logo">
            </div>
            <div class="container">
                <form action="{% url 'specimen_search_results' %}" method="GET" class="form-inline">
                    {{ forms.toggle }}&nbsp&nbsp{{ forms.search_bar }}
                    &nbsp;<button type="submit" class="btn btn-primary">Search</button>
                    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#addSpecimenModal"
                        style="float: right;">
                        Add Specimen Record
                    </button>
                        {% block content %}
                {% if user.is_authenticated %}
                  Hi {{ user.username }}!
                  <p><a href="{% url 'logout' %}">Log Out</a></p>
                {% else %}
                  <p>You are not logged in</p>
                  <a href="{% url 'login' %}">Log In</a>
                {% endif %}
                {% endblock %}
                </form>
    
                <!-- Modal -->
                <div class="modal fade" id="addSpecimenModal" tabindex="-1" role="dialog" aria-labelledby="addSpecimenModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="addSpecimenModalLabel">Add Specimen Record</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                               <form method="post" id="specimenForm" data-species-url="{% url 'get_species' %}" novalidate>
                                {% csrf_token %}
                                <table>
                                    {% for field in spec_form %}
                                    <tr>
                                        <th>{{ field.label_tag }}</th>
    
                                        <td>
                                            {% if field.label == 'spec_id' %}
                                                {{ field }}
                                                <button type="button" class="tooltip-icon" data-toggle="tooltip" data-placement="top" title="{{ field.help_text }}">i</button>
                                            {% else %}
                                                {{ field }}
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% endfor %}
                                    </table>
                                    <button type="submit" class="btn btn-default" form="specimenForm">Add Record</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
    
                <!-- Display the Table -->
                {% if table %}
                {% render_table table %}
                {% else %}
                <p>No results found.</p>
                {% endif %}
            </div>
    
            <!-- Include Bootstrap JS and jQuery -->
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    
    <script>
        // Event handler for the class dropdown.
        $("#id_tclass").change(function () {
            var url = $("#specimenForm").attr('data-species-url');
            var classID = $(this).val();
            var selectedField = 'class';
    
            $.ajax({
                url: url,
                data: {
                    'id': classID,
                    'selected_field': selectedField,
                },
                success: function (data) {
                    $("#id_order").html(data);
                }
            });
        });
    
        // Event handler for the order dropdown.
        $("#id_order").change(function () {
            var url = $("#specimenForm").attr('data-species-url');
            var orderID = $(this).val();
            var selectedField = 'order';
    
            $.ajax({
                url: url,
                data: {
                    'id': orderID,
                    'selected_field': selectedField,
                },
                success: function (data) {
                    $("#id_family").html(data);
                }
            });
        });
    
        // Event handler for the family dropdown.
        $("#id_family").change(function () {
            var url = $("#specimenForm").attr('data-species-url');
            var familyID = $(this).val();
            var selectedField = 'family';
    
            $.ajax({
                url: url,
                data: {
                    'id': familyID,
                    'selected_field': selectedField,
                },
                success: function (data) {
                    $("#id_genus").html(data);
                }
            });
        });
    
        // Event handler for the genus dropdown.
        $("#id_genus").change(function () {
            var url = $("#specimenForm").attr('data-species-url');
            var genusID = $(this).val();
            var selectedField = 'genus';
    
            $.ajax({
                url: url,
                data: {
                    'id': genusID,
                    'selected_field': selectedField,
                },
                success: function (data) {
                    $("#id_species").html(data);
                }
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $('#home').DataTable();
        });
    </script>
    </body>
    </html>
    
    #search_results.html
    <!DOCTYPE html>
    <html lang="es">
    <head>
        <title>Specimen Table</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>
    <style>
        .center-logo {
            display: block;
            margin: 0 auto;
            text-align: center;
            padding-top: 0px;
            padding-bottom: 0px;
            transform: scale(0.8);
        }
    </style>
    <body>
        <div class="container">
            <div class="text-center">
                {% load static %}
                <img src="{% static 'zombie/logo.png' %}" alt="Your Image" class="center-logo">
            </div>
            <div class="container">
                <form action="{% url 'specimen_search_results' %}" method="GET" class="form-inline">
                    {{ forms.toggle }}&nbsp&nbsp{{ forms.search_bar }}
                    &nbsp;<button type="submit" class="btn btn-primary">Search</button>
                    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#addSpecimenModal"
                        style="float: right;">
                        Add Specimen Record
                    </button>
                </form>
    
                <!-- Modal -->
                <div class="modal fade" id="addSpecimenModal" tabindex="-1" role="dialog" aria-labelledby="addSpecimenModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="addSpecimenModalLabel">Add Specimen Record</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                               <form method="post" id="specimenForm" data-species-url="{% url 'get_species' %}" novalidate>
                                {% csrf_token %}
                                <table>
                                    {% for field in spec_form %}
                                    <tr>
                                        <th>{{ field.label_tag }}</th>
    
                                        <td>
                                            {% if field.label == 'spec_id' %}
                                                {{ field }}
                                                <button type="button" class="tooltip-icon" data-toggle="tooltip" data-placement="top" title="{{ field.help_text }}">i</button>
                                            {% else %}
                                                {{ field }}
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% endfor %}
                                    </table>
                                    <button type="submit" class="btn btn-default" form="specimenForm">Add Record</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
    
            {% if table %}
                {% load render_table from django_tables2 %}
                {% render_table table %}
            {% else %}
                <p>No results found.</p>
            {% endif %}
        </div>
    
        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
        <script>
            $(document).ready(function () {
                $('#home').DataTable();
            });
        </script>
    </body>
    </html>

以下是视图

@login_required
def HomeTableView(request):
    from zombie.models import Master_Table
    forms = SpecimenSearchForm()
    queryset = Master_Table.objects.all()
    table = HomeTable(queryset)

    if request.method == 'POST':
        spec_form = SpecimenForm(request.POST)
        if spec_form.is_valid():
            try:
                new_specimen = spec_form.save()
            except Exception as e:
                print(e)
            return redirect('home')
    else:
        spec_form = SpecimenForm()

    return render(request, 'zombie/home.html',
                  {'table': table.paginate(page=request.GET.get("page", 1)), 'forms': forms, 'spec_form': spec_form})

@login_required
def SearchResultsView(request):
    from zombie.models import Master_Table
    forms = SpecimenSearchForm()
    page = request.GET.get('page')

    value = request.GET.get('search_bar')
    param = request.GET.get('toggle')
    if param =='t':
        print(value)
        tax = Master_Table.objects.filter(
            Q(t_class=value) |
            Q(torder=value) |
            Q(family=value) |
            Q(genus=value) |
            Q(species__icontains=value)
        )
        print(tax)
        table = HomeTable(tax)
        context = {
                'forms': forms,
                'table': table.paginate(page=request.GET.get("page", 1))
            }
        return render(request, 'zombie/search_results.html', context)


    elif param=='s':
        query = Master_Table.objects.filter(id__icontains=value)
        print(query)
        table = HomeTable(query)
        context = {
            'forms': forms,
            'table': table.paginate(page=request.GET.get("page", 1))
        }
        return render(request, 'zombie/search_results.html', context)

    elif param == 'c':
        query = Master_Table.objects.filter(common_name__icontains=value)
        table=HomeTable(query)
        context = {
            'forms': forms,
            'table': table.paginate(page=request.GET.get("page", 1))
        }
        return render(request, 'zombie/search_results.html', context)
    elif param == 'cl':
        query = Master_Table.objects.filter(collector__icontains=value)
        table = HomeTable(query)
        context = {
            'forms': forms,
            'table': table.paginate(page=request.GET.get("page", 1))
        }
        return render(request, 'zombie/search_results.html', context)
    elif param=='type':
        sample_query = Sample.objects.values_list('specimen_id').filter(sample_type=value)
        sample_query = list(sample_query)
        specimen_ids = []
        for id in sample_query:
            if len(id) > 0:
                specimen_ids.append(id[0].split("'")[0])
        specimen_query = Master_Table.objects.filter(id__in = specimen_ids)
        table = HomeTable(specimen_query)
        context = {
            'forms': forms,
            'table': table.paginate(page=request.GET.get("page", 1))
        }

        return render(request, 'zombie/home.html', {'table': table.paginate(page=request.GET.get("page", 1)), 'forms': forms})
    elif param=='status':
        sample_query = Sample.objects.values_list('specimen_id').filter(status=value)
        sample_query = list(sample_query)
        specimen_ids = []
        for id in sample_query:
            if len(id) > 0:
                specimen_ids.append(id[0].split("'")[0])
        specimen_query = Master_Table.objects.filter(id__in=specimen_ids)
        table = HomeTable(specimen_query)
        context = {
            'forms': forms,
            'table': table.paginate()
        }

        return render(request, 'zombie/home.html', {'table': table.paginate(page=request.GET.get("page", 1)), 'forms': forms})
    else:
        queryset = Master_Table.objects.all()
        table = HomeTable(queryset)
        return render(request, 'zombie/home.html', {'table': table.paginate(page=request.GET.get("page", 1)), 'forms': forms, })
django django-forms bootstrap-modal

评论


答:

0赞 Mess 11/7/2023 #1

使用视图的当前设置,对视图发出 get 请求将返回一个空表单,因为您没有传入样本的模型实例。EditSpecimenView

试试这个。

def EditSpecimenView(request,pk):
    instance = Specimen.objects.get(specimen_id=pk)
    if request.method == 'POST':
        specimen_update_form = UpdateSpecimenForm(request.POST, instance=instance)
        if specimen_update_form.is_valid:
            specimen_update_form.save()
            return redirect('home')
    else:
        specimen_update_form = UpdateSpecimenForm(instance=instance)

    context = {'spec_form': specimen_update_form}

    return render(request, 'zombie/edit_record.html', context)

评论

0赞 leah3333 11/8/2023
我刚刚尝试了您的建议,但它仍然没有呈现表单。弹出窗口出现,但没有表单。而且似乎没有向视图发送任何请求,因为如果我打印请求,当我单击编辑按钮时不会显示任何内容。
0赞 Mess 11/8/2023
在进入试样详细信息视图之前,您能否显示负责显示试样列表的 HTML 模板和视图
0赞 leah3333 11/8/2023
我只是在上面把它们加起来。谢谢
0赞 leah3333 11/11/2023
此外,问题在于它根本没有呈现表单。因此,弹出窗口出现,但根本没有表单或输入字段