Как добавить опцию вычитания в таблицу в Django - PullRequest
1 голос
/ 25 апреля 2019

Я делаю свое первое заявление с Джанго. Цель состоит в том, чтобы иметь таблицу, которая отображает текущий инвентарь лабораторных реагентов. Как только реагент вынут из хранилища, пользователь сможет нажать кнопку вычитания, чтобы вычесть текущий инвентарь. В настоящее время у меня есть таблица, которая отображает название и количество реагента. Я хотел бы добавить в таблицу столбец с кнопкой вычитания, которая будет вычитать один из соответствующих запасов текущего реагента.

Может ли кто-нибудь дать мне несколько советов о том, как реализовать кнопку вычитания? Любая помощь приветствуется.

models.py
class Reagentquant(models.Model):

    Name_Of_Reagent= models.TextField()
    Reagent_Quantity= models.TextField()
tables.py

class ReagentquantTable(tables.Table):
    class Meta:
        model = Reagentquant
        template_name = 'django_tables2/bootstrap4.html'
        row_attrs = {'reagent_id': 'reagent'}
    edit= TemplateColumn(template_name='inventory/update_column.html')
views.py

def reagentquant(request):
    table = ReagentquantTable(Reagentquant.objects.all())
    RequestConfig(request).configure(table)
    return render(request, 'inventory/quant.html', {'table': table})


class RemoveReagentView:
    def post(self, request, *args, **kwargs):
        reagent_id = request.POST['reagent_id']
        reagent = Reagentquant.objects.filter(id=reagent_id)

        reagent.update(Reagent_Quantity=F('Reagent_Quantity')-1)
        data = {"count": reagent.Reagent_Quantity}
        return JsonResponse(data)
template 

<a class="btn btn-info btn-sm">-</a>

<script type="text/javascript">

  $(document).on('click', 'odd', function (e) {  // Where `element_with_reagentID_class` is the common classname of ALL elements that have your `reagent_id` inserted into them
      e.preventDefault();

      var $this = $(this);
      var reagent_id = $this.attr('reagent')  // Where `reagent_id` is whatever the attribute is that you added

      $.ajax({
          type: "POST",
          url: "{% url 'inventory-quant' %}",  // Where `reagent_urlname` is the name of your URL specified in urls.py
          data: {reagent_id: reagent_id, csrfmiddlewaretoken: "{{ csrf_token }}"}
      })
      .done(function (response){
          console.log(response)
      })
  })}


</script>

/script>
</td>

                    </tr>



                    <tr scope="row" reagent_id="reagent" class="odd">

                            <td >17</td>

                            <td >CRP</td>

                            <td >22</td>

                            <td >

<a class="btn btn-info btn-sm" onClick="testMe()">-</a>

<script type="text/javascript">

  $(document).on('click', 'reagent', function (e) {  // Where `element_with_reagentID_class` is the common classname of ALL elements that have your `reagent_id` inserted into them
      e.preventDefault();

      var $this = $(this);
      var reagent_id = $this.attr('reagent')  // Where `reagent_id` is whatever the attribute is that you added

      $.ajax({
          type: "POST",
          url: "/quant",  // Where `reagent_urlname` is the name of your URL specified in urls.py
          data: {reagent_id: reagent_id, csrfmiddlewaretoken: "NjfgIlWzzSBwq8EJh5jsdIqns4tK6tMFLH4vEkUSWAHW5VCHigpVpmzkDPBwbyL3"}
      })
      .done(function (response){
          console.log(response)
      })
  })}


</script>
</td>

                    </tr>



                    <tr scope="row" reagent_id="reagent" class="even">

                            <td >20</td>

                            <td >MTX</td>

                            <td >22</td>

                            <td >

1 Ответ

0 голосов
/ 25 апреля 2019

Чтобы обновить количество, вы можете сделать что-то вроде этого:

class RemoveReagentView(View):
    def post(self, request, *args, **kwargs):
        reagent_id = request.POST['reagent_id']
        reagent = Reagentquant.objects.filter(id=reagent_id)

        reagent.update(Reagent_Quantity=F('Reagent_Quantity')-1)
        data = {"count": reagent.Reagent_Quantity}
        return JsonResponse(data)

Следующим шагом будет подключение к рендерингу django_tables2.Лучше всего было бы добавить пользовательский атрибут строки значения reagent.id, захватить его с помощью Javascript, а затем использовать запрос AJAX POST для вызова представления RemoveReagentView(), которое я указал выше.Очевидно, вам также понадобится кнопка +/-, которую, кажется, вы можете добавить, используя что-то вроде этого ответа.

В целом, для этого понадобится немного умного взлома,но это кажется очень выполнимым.

edit

Вот пример запроса AJAX:

$(document).on('click', '.element_with_reagentID_class', function (e) {  // Where `element_with_reagentID_class` is the common classname of ALL elements that have your `reagent_id` inserted into them 
    e.preventDefault();

    var $this = $(this);
    var reagent_id = $this.attr('reagent_id')  // Where `reagent_id` is whatever the attribute is that you added

    $.ajax({
        type: "POST",
        url: "{% url 'reagent_urlname' %}",  // Where `reagent_urlname` is the name of your URL specified in urls.py
        data: {reagent_id: reagent_id, csrfmiddlewaretoken: "{{ csrf_token }}"} 
    })
    .done(function (response){
        console.log(response)
    })
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...