如何将HTML表中的记录从一个表模型中获取的数据添加到另一个表模型中?

2024-10-02 22:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

首先是关于我的。。。我只是一个初级Python和Django开发人员,所以我正在学习并应用我在实际工作项目中学到的东西。你知道吗

问题

我正在为我工作的医院构建一个小的药房管理应用程序,我想在那里创建一个药品可用性跟踪列表,医生可以在其中检查药品是否可用,以便他们可以编写患者处方。你知道吗

我做了什么?你知道吗

我有一个国家药品处方集(Formulario Nacional de Medicamentos)的表格模型,我的Django中描述了我国(古巴)使用的所有药品和药理产品的完整列表型号.py作为:

class FarmMedicamento(models.Model):
    meddesc = models.CharField(max_length=250)
    presentacion = models.ForeignKey(FarmPresentacion, models.DO_NOTHING)
    forma_presentacion = models.CharField(max_length=250, blank=True, null=True)

    def __str__(self):
        return ("%s - %s %s" % (self.meddesc, str(self.presentacion).upper(), self.forma_presentacion))

    def propiedad_colname(self):
        return ("%s - %s %s" % (self.meddesc, str(self.presentacion).upper(), self.forma_presentacion))

    propiedad_colname.short_description = 'Medicamento'

    columna_medicamento = property(propiedad_colname)

    class Meta:
        managed = False
        db_table = 'farm_medicamento'
        verbose_name = "Medicamento"
        verbose_name_plural = 'Medicamentos'

我将药品可用性存储在另一个表模型中,如所述:

class FarmExistencia(models.Model):

    medid = models.OneToOneField(FarmMedicamento, models.DO_NOTHING, primary_key=True, verbose_name="Medicamento")
    disponible = models.BooleanField("Disponible")
    actualizado = models.DateTimeField(auto_now=True)

    class Meta:
        managed = True
        db_table = 'farm_existencia'
        verbose_name = "Disponibilidad de medicamento"
        verbose_name_plural = 'Disponibilidad de medicamentos'

    def __str__(self):
        return ("%s" % (self.medid))

药品列表视图是:

class FarmMedicamentoListView(LoginRequiredMixin, ListView):
    model = FarmMedicamento
    context_object_name = 'listado_fnm'
    template_name = 'existencias/farmmedicamento_list.html'

    def get_context_data(self, **kwargs):
        context = super(FarmMedicamentoListView, self).get_context_data(**kwargs)
        context['disponibles'] = FarmExistencia.disponibles.all()
        context['agotados'] = FarmExistencia.agotados.all()
        return context

我想要什么?你知道吗

我想在主列表中按加号按钮添加新的可用药品,并立即更新“可用药品”的绿色部分,但我不知道怎么做。你知道吗

我的实际模板列表截图:https://i.imgur.com/yNr7jic.png

模板的HTML

{% extends 'base.html' %}
{% load static %}
{% block title %}AllenFarma | Listado de medicamentos {% endblock title %}
{% block head %}
    <link href="{% static 'css/datatables.min.css' %}" rel="stylesheet" type="text/css" />
    <script src="{% static 'js/datatables.min.js' %}"></script>
    <style rel="stylesheet" type="text/css">
    .table > tbody > tr > td.item_add-control {
        background: url('/static/images/icons/add_button.png') no-repeat center center;
        cursor: pointer;
        padding: 8px 12px 8px 12px;
    }
    .table > tbody > tr > td.item_remove-control {
        background: url('/static/images/icons/remove_button.png') no-repeat center center;
        cursor: pointer;
        padding: 8px 12px 8px 12px;
    }
    </style>
{% endblock head %}
{% block content %}
<div class="container">
    <div class="col-md-6">
        <div class="panel panel-success">
            <div class="panel-heading">
                <div style="text-align:left" class="panel-title">Medicamentos en existencia</div>
            </div>
            <div style="padding-top:10px" class="panel-body">
                {% include 'existencias_list.html' %}
            </div>
        </div>
    </div>
    <div class="col-md-6">    
        <div class="panel panel-danger">
            <div class="panel-heading">
                <div style="text-align:left" class="panel-title">Medicamentos agotados</div>
            </div>
            <div style="padding-top:10px" class="panel-body">
                {% include 'agotados_list.html' %}
            </div>
        </div>
    </div>
    <div class="col-md-12">    
        <div class="panel panel-info">
            <div class="panel-heading">
                <div style="text-align:left" class="panel-title">Medicamentos del Formulario Nacional de Medicamentos</div>
            </div>
            <div style="padding-top:10px" class="panel-body">
                <table id="listado_medicametos" class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>Medicamentos</th>
                            <th>Presentación</th>
                            <th>Forma de presentación</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                    {% for medicamento in listado_fnm %}
                    <tr>
                        <td>{{medicamento.meddesc}}</td>
                        <td>{{medicamento.presentacion}}</td>
                        <td>{{medicamento.forma_presentacion}}</td>
                        <td id="add_control"></td>
                    </tr>
                    {% endfor %}
                    </tbody>
                    <tfoot>
                        <tr>
                        </tr>
                    </tfoot>

                </table>
            </div>
        </div>
    </div>    
</div>
<script type="text/javascript">
$(document).ready( function () {
    $('#listado_medicametos')
        .dataTable({
            "columns": [
                {"data": "meddesc"},
                {"data": "presentacion"},
                {"data": "forma_presentacion"},
                {
                    "class":          "item_add-control",
                    "orderable":      false,
                    "data":           null,
                    "defaultContent": ""
                },
            ],
            "order": [[0, 'asc']],
            "language": {
                "url": "/static/i18n/es_ES.json"
            },
            scrollY: 230
        });
});
</script>
{% endblock content %}

Tags: nameselfdivstylemodelstabletrclass
2条回答

解决此类问题的基本工作流可以是一个Ajax调用,用于将更改发布到Django服务器;一个Django视图,用于接收和实现模型中的更改,并响应Ajax调用,Ajax调用根据所做的任何更新更新HTML。你知道吗

一个简单的例子:

Javascript:

您需要一个Ajax方法,当您单击add/remove按钮并将药品的ID发布到Django视图时触发该方法,您可以在该视图中将其设置为available/unavailable。你知道吗

$('.addButton').on('click', function(event){
    $.ajax({
        url : '/add/medicine/url/',
        type : 'POST',
        data : {'medicine_id': id, csrfmiddlewaretoken: 'your csrftoken' },
        success: function(json) {
            // Successful response, so you can update the medicine list HTML using JQuery here.
        },
    });
});

视图.py

from django.http import JsonResponse

def add_medicine(request):
    if request.method == 'POST':
        medicine_id = int(request.POST.get('medicine_id'))
        medicine = Medicine.objects.get(id=medicine_id)
        medicine.available = True
        medicine.save()
        return JsonResponse({'medicine_id': medicine_id}, status=200)

这是一个例子来说明工作流程,命名不匹配您的代码。另外,我认为应该在医学模型本身中指定药物可用性,而不是在两个单独的模型中,或者至少在两个模型之间有一些back-ref关系,这样就可以通过另一个模型访问其中一个,反之亦然。你知道吗

由于您希望通过管理界面添加新药并自动刷新列表,因此必须编写一个Javascript函数来加载数据并填充可用药物的列表。你知道吗

JS函数应该周期性地执行(使用计时器)并调用Django视图,该视图提供要在那里显示的数据。你知道吗

相关问题 更多 >