如何在不刷新的情况下正确呈现页面中数据库的字段?

时间:2019-11-04 17:23:20

标签: python jquery html django ajax

我试图在一个框的顶部显示用户名,在该框内他们以表格形式输入其雇员编号,而不必刷新页面,例如,他们输入其编号,然后单击/制表到下一个字段,它将名称显示在顶部,因此用户知道他们输入了正确的信息。此名称也存储在单独的模型中,因此我尝试使用“ id /数字”来检索它。

我不太熟悉AJAX,但是在阅读了一些类似的问题之后,看来AJAX请求将是实现此目标的最合适方法。我试图创建一个函数 get_employee_name ,该函数根据我看到另一个ajax请求的工作方式返回该人的名字,但是我不确定如何实现它,因此在输入#后显示

models.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)

    def __str__(self):
        return self.employee_number

这是存储名称的模型

alldata / models.py

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

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

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

    def form_valid(self, form):
        emp_num = form.cleaned_data['employee_number']
        area = form.cleaned_data['work_area']
        station = form.cleaned_data['station_number']

        if 'enter_area' in self.request.POST:
            form.save()
            return HttpResponseRedirect(self.request.path_info)

        elif 'leave_area' in self.request.POST:
            form.save()
            EmployeeWorkAreaLog.objects.filter(employee_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now())
            return HttpResponseRedirect(self.request.path_info)


def get_employee_name(request):
    employee_number = request.GET.get('employee_number')
    employee = Salesman.objects.get(employee_number=employee_number)
    employee_name = employee.slsmn_name
    return employee_name

urls.py

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

    path('get-employee-name/<int:id>/', views.get_employee_name, name='employee_name'),
]

enter_exit_area.html

{% extends "base.html" %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" novalidate >
        {% csrf_token %}
        <div>
            <h1 id='employee_name'></h1>
            <div>
                {{ form.employee_number.help_text }}
                {{ form.employee_number }}
            </div>
            <div>
                {{ form.work_area.help_text }}
                {{ form.work_area }}
            </div>
            <div>
                {{ form.station_number.help_text }}
                {{ form.station_number }}
            </div>
        </div>

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

    <script>
        $("#employee_number_field").change(function () {
            var employee_number = $(this).val();
            var url = 'get-employee-name/' + employee_number;

            $.ajax({
                url: url,
                type:'post',
                data: {
                    'id': employee_number
                },
                success: function (data) {
                    employee_name = data;
                    $('#employee_name')[0].innerHTML = employee_name;
                }
            });
        });
    </script>
{% endblock main %}

employee_name.html

<h2>{{ employee_name }}</h2>

0 个答案:

没有答案