Django Форма - Выберите внешний ключ из bootstrap модального всплывающего окна - PullRequest
0 голосов
/ 27 марта 2020

Я создал модальное всплывающее окно js / ajax в форме, чтобы помочь выбрать параметр для поля внешнего ключа в форме. Я заблудился о том, как передать выбранную переменную обратно в форму и закрыть модальные. Вот мой код:

views.py
def worker_wizard_popup(request, pk):

    data = dict()
    shift = Shift.objects.get(id=pk)
    skilled = EmployeeSkill.objects.filter(skill_id=shift.skill.id).values_list('employee_id', flat=True)
    on_other_shifts = ShiftWorker.objects.filter(shift_date=shift.date, employee_id__in=skilled).order_by('employee__first_name')
    on_other_shifts_ids = on_other_shifts.values_list('employee_id', flat=True)
    time_off = TimeOff.objects.filter(start_date__lte=shift.date, end_date__gte=shift.date, employee_id__in=skilled).exclude(Q(start_date=shift.date, start_time__gte=shift.shift_start)|Q(end_date=shift.date, end_time__lte=shift.shift_start)).order_by('employee__first_name')
    time_off_ids = time_off.values_list('employee_id', flat=True)
    available = User.objects.filter(id__in=skilled, is_active=True).exclude(Q(id__in=on_other_shifts_ids)|Q(id__in=time_off_ids)|Q(admin=True)).order_by('first_name')

    context = {
        'shift': shift,
        'on_other_shifts': on_other_shifts,
        'time_off': time_off,
        'available': available
    }
    data['html_form'] = render_to_string('events/includes/partial_availability_wizard.html',
        context,
        request=request,
    )
    return JsonResponse(data)

Вот форма, в которой я хочу, чтобы выбранный FK перешел к выбранной опции поля Сотрудник.

<div class="col-lg-6 mb-4 bg-default">
      <div class="card">
        <div class="card-header">Add Worker</div>
        <div class="card-block">
          {% bootstrap_form_errors form %}
        <form method='POST'>
            {% csrf_token %}

            <button type="button" class="btn btn-info btn-md js-worker-wizard mb-2" data-url="{% url 'events:worker_wizard' pk=shift.id %}"><span class="fas fa-hat-wizard fa-lg"></span> Shift Wizard</button>
            {% bootstrap_field form.employee %}
            {% bootstrap_field form.shift_date %}
            {% bootstrap_field form.shift_start %}
            {% bootstrap_field form.shift_end_date %}
            {% bootstrap_field form.shift_end_time %}
            {% bootstrap_field form.call_location %}
            {% bootstrap_field form.pay_rate %}

            {% if request.tenant.preferences.request_confirm == True %}
            {% bootstrap_field form.request_confirm %}
            {% endif %}
            {% bootstrap_field form.notification %}


            {% bootstrap_button "Save" button_type="submit" button_class="btn-primary"%}
        </form>

            </div>
        </div>
    </div>

Это html для модального всплывающего окна. Кнопка ввода находится в первом столбце таблицы

<table id="available" class="table table-striped table-bordered" cellspacing="0" width="100%">
                <thead>
                  <tr>
                    <th></th>
                    <th>Worker</th>
                    <th>Location</th>
                    <th>Transportation</th>
                  </tr>
                </thead>
                <tbody>
                  {% for worker in available %}
                  <tr>
                    <td><input type="submit" value="Select"></td>
                    <td>{{worker.get_full_name}}</td>
                    <td>
                    {% if worker.city and worker.state %}
                      {{worker.city}}, {{worker.state}}
                    {% elif worker.state %}
                      {{worker.state}}
                    {% endif %}
                    </td>
                    <td>
                    {% if worker.transportation %}

                      {% if worker.transportation == True %}
                        Yes
                      {% else %}
                        No
                      {% endif %}

                    {% else %}
                    Unkown
                    {% endif %}
                      </td>
                  </tr>
                  {% empty %}
                  <tr>
                    <td colspan="4" class="text-center" style="background-color:red; font-weight: bold;">Uh Oh! No available {{shift.skill.name}} workers</td>
                  </tr>
                  {% endfor %}
                </tbody>
              </table>

и javascript:

$(function () {

  /* Functions */

  var loadDetail = function () {
    var btn = $(this);
    $.ajax({
      url: btn.attr("data-url"),
      type: 'get',
      dataType: 'json',
      success: function (data) {
        $("#modal-event .modal-content").html(data.html_form);
        $("#modal-event").modal("show");
      },
    });
  };



  // 
  $(".js-worker-wizard").click(loadDetail);

});

Я все еще новичок здесь, поэтому я прошу прощения, если я не спросил это должным образом , Если вы можете помочь с решением или как мне лучше сообщить вопрос, пожалуйста, дайте мне знать!

...