简体   繁体   English

如何在不刷新页面的情况下正确显示存储在外部 model 中的数据?

[英]How to correctly display data stored in an external model without refreshing the page?

I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page.我试图在一个框的顶部显示用户的姓名,他们在表单中输入员工编号,而无需刷新页面。

For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info.例如,他们输入他们的#,然后在他们单击/tab 进入下一个字段后,它会将他们的名字呈现在顶部,该名字来自数据库,因此用户知道他们输入了正确的信息。 This name is stored in a separate model, so I try to retrieve it using the "id/number".此名称存储在单独的 model 中,因此我尝试使用“id/number”检索它。

I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this.我对 AJAX 不太熟悉,但在阅读了一些类似的问题后,似乎 AJAX 请求将是实现此目标的最合适方法。 I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered.我试图制作一个 function get_employee_name根据我看到另一个 ajax 请求工作的方式返回人的姓名,但我不确定如何实现它,因此它会在输入 # 后显示。

My page currently loads, but when I check the network using F12, there is never a call to the function/url that searches for the name to display it on the page.我的页面当前正在加载,但是当我使用 F12 检查网络时,永远不会调用搜索名称以将其显示在页面上的函数/url。 I'm not sure where I might be missing the part that connects these two areas of the code, but I have a feeling it has to do with the html tag where the call is supposed to happen, as I am not too familiar with html and Django.我不确定我可能在哪里遗漏了连接代码的这两个区域的部分,但我觉得它与 html 标签有关,因为我不太熟悉 html和 Django。

models.py模型.py

class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
    work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False)
    station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True,  blank=True)

This is the model where the name is stored这是存储名称的 model

alldata/models.py所有数据/模型.py

class Salesman(models.Model):
    slsmn_name = models.CharField(max_length=25)
    id = models.IntegerField(db_column='number', primary_key=True)

I was reading I can add to the "attrs" in the widget an 'onchange' part, but I am not too familiar with how to approach this and tying it to the ajax request from forms and not the html.我正在阅读我可以在小部件的“属性”中添加一个“onchange”部分,但我不太熟悉如何处理这个问题并将其与来自 forms 的 ajax 请求联系起来,而不是 ZFC35FDC70D2FC69D26EZC57A77A7。

forms.py forms.py

class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
        }
        fields = ('employee_number', 'work_area', 'station_number')

views.py视图.py

class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "operations/enter_exit_area.html"
    form_class = WarehouseForm

    def form_valid(self, form):
        # do submission stuff..


def get_employee_name(request):
    employee_number = request.GET.get('employee_number')

    try:
        employee = Salesman.objects.get(id=employee_number)
    except Salesman.DoesNotExist:
        return JsonResponse({'error': 'Employee not found'}, status=404)

    employee_name = employee.slsmn_name
    return JsonResponse({'employee_name': employee_name})

urls.py网址.py

urlpatterns = [
    url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),

    path('ajax/load-stations/', views.load_stations, name='ajax_load_stations'),
    path('get-employee-name/', views.get_employee_name, name='ajax_get_employee_name'),
]

The ajax request I tried to create is at the end of this html.我尝试创建的 ajax 请求位于此 html 的末尾。 I modified a similar request I found, but it does not actually display anything on the screen, not sure if I'm missing an area where the request is actually never being called, as I am not too familiar with how these types of requests work.我修改了我发现的类似请求,但它实际上并没有在屏幕上显示任何内容,不确定我是否错过了实际上从未调用过请求的区域,因为我不太熟悉这些类型的请求如何工作.

enter_exit_area.html enter_exit_area.html

{% extends "base.html" %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
        {% csrf_token %}
        <div>
            <h1 get-employee-name-url="{% url 'operations:ajax_get_employee_name' %}"></h1>
            <div>
                {{ form.employee_number.help_text }}
                {{ form.employee_number }}
            </div>
            <div>
                {{ form.work_area.help_text }}
                {{ form.work_area }}
            </div>
        </div>

        <div>
            <div>
                <button type="submit" name="enter_area" value="Enter">Enter Area</button>
            </div>
        </div>
    </form>

<!-- This is the dependent dropdown script -->

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
        $("#id_work_area").change(function () {
            var url = $("#warehouseForm").attr("data-stations-url");
            var workAreaId = $(this).val();

            $.ajax({
                url: url,
                data: {
                    'work_area': workAreaId
                },
                success: function (data) {
                    $("#my-hidden-div").show(); // show it
                    $("#id_station_number").html(data);
                    // Check the length of the options child elements of the select
                    if ($("#id_station_number option").length == 1) {
                        $("#id_station_number").parent().hide(); // Hide parent of the select node
                    } else {
                        // If any option, ensure the select is shown
                        $("#id_station_number").parent().show();
                    }
                }
            });
        });
     </script>

<!-- -->

    <script>
        $("#id_employee_number").change(function () {
            var employee_number = $(this).val();
            var url = $("#warehouseForm").attr("get-employee-name-url");

            $.ajax({
            url: url,
            type:'GET',
            data: {
                'id': employee_number
            },
            success: function (data) {
                var employee_name = data['employee_name'];
                $('#employee_name')[0].innerHTML = employee_name;
            },
            error : function (data) {
                var error_message = data['error'];
                $('#employee_name')[0].innerHTML = error_message;
            }
            });
        });
    </script>

{% endblock main %}

What could be causing nothing to render on the page?什么可能导致页面上没有任何内容? Is there a call missing in the html portion? html 部分中是否缺少呼叫?

I assume there needs to be a place where the onchange() goes, but I'm not sure where this would be in since the form fields are it's own thing, without tags.我认为需要有一个地方 onchange() 去,但我不确定它会在哪里,因为表单字段是它自己的东西,没有标签。

With regards to关于

var url = $("#warehouseForm").attr("get-employee-name-url");

The id is referring to the form which does not have an attribute name "get-employee-name-url". id 是指没有属性名称“get-employee-name-url”的表单。 Your url is actually in here你的 url 实际上在这里

<h1 get-employee-name-url="{% url 'operations:ajax_get_employee_name' %}"></h1>

So maybe add an id to it like this所以也许像这样添加一个id

<h1 id="url" get-employee-name-url="{% url 'operations:ajax_get_employee_name' %}"></h1>

and then you can access it like you were然后你可以像以前一样访问它

var url = $("#url").attr("get-employee-name-url");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不刷新页面的情况下渲染存储在外部model中的一段数据? - How to render a piece of data stored in an external model without refreshing the page? 如何在不刷新页面的情况下显示/呈现存储在外部 model 中的用户名? - How to display/render User's name stored in an external model without refreshing the page? 如何在不刷新的情况下从外部页面更新内容div-GAE - How to update content div from an external page without refreshing - GAE Django + AJAX查询模型,无需刷新页面 - Django + AJAX query model without refreshing the page Django 如何在不刷新或重新加载页面的情况下插入数据 - Django How do i Insert data without refreshing or reloading page [Django]提交表单后如何显示消息(正确或错误),而不刷新页面? - [Django]How to display a message(correct or incorrect) after submitting the form, without refreshing the page? 如何在 django 中自动更新页面而不刷新? - How to automatically update a page without refreshing in django? Django:如何在不刷新页面的情况下更新图像? - Django: How to update an image without refreshing the page? 如何在不刷新页面的情况下自动重装Flask中的Jinja 2数据? - How to do auto-reloading of jinja 2 data in Flask without refreshing page? 如何从模型中获取数据并显示在产品页面上? - How to take data from model and display on the product page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM