Django“ adminlike”外键添加按钮

时间:2018-09-01 18:33:31

标签: jquery ajax django

因此,我有一个与客户具有外键关系的交付模型。我想介绍“添加外键”按钮,就像管理区域一样。

我已经阅读了此处显示的自定义窗口小部件上的线程:Django: adding an “Add new” button for a ForeignKey in a ModelForm 不幸的是我无法正常工作,所以我尝试了另一种方法。

在发送表单中,我添加了一个“添加客户”按钮。此按钮打开一个模式,该模式显示一个表单,用于使用ajax添加客户。

因此,我开始处理表单,它在不离开交货表单区域的情况下向数据库添加了新客户。诀窍是,我想在客户下拉列表中选择新添加的客户。

我需要从新创建的客户那里检索customer.id,并在下拉菜单中选择他或她,这就是我被困住的原因。该ID在客户表单中尚不可用,因此我必须使用GET ...从数据库中检索该ID。

对此有何想法?任何帮助将不胜感激!

urls.py

urlpatterns += [  # Links to create, update and delete deliveries
url(r'^delivery/create/$', login_required(views.DeliveryCreate.as_view()), name='delivery_create'),
url(r'^delivery/add_customer/$', login_required(views.delivery_add_customer), name='delivery_add_customer'),
]

views.py

# A function based view to add a customer on the fly in the delivery form
def delivery_add_customer(request):
data = dict()

if request.method == 'POST':
    form = CustomerForm(request.POST)
    if form.is_valid():
        form.save()
        data['form_is_valid'] = True

    else:
        data['form_is_valid'] = False

else:
    form = CustomerForm()

context = {'form': form}
data['html_form'] = render_to_string('includes/partial_delivery_add_customer.html',
    context,
    request=request
)

return JsonResponse(data)

delivery_form.html

{% block content %}
<div id="modal_form" class="modal">
  <div class="modal-content"></div>
</div><!-- End of modal -->
<div class="container">
  <div class="row">
    <div class="card">
        <div class="card-action">
            <button class="btn orange modal-trigger js-delivery-add-customer" data-url="{% url 'delivery_add_customer' %}">
                <i class="material-icons btn__icon">add</i>
                Add Customer
            </button>
        </div>
        <form class="form-on-card" action="" method="POST">
          {% csrf_token %}
          {% form form=form %}
          {% endform %}
          <input button class="waves-effect waves-light btn" type="submit" value="Add" /></button>
        </form>
    </div>
  </div><!-- End of row -->
</div><!-- End of container -->
{% endblock %}

partial_delivery_add_customer.html

<form class="form-on-card--modal modal-trigger js-add-customer-form" action="{% url 'delivery_add_customer' %}" method="POST" novalidate>
<div class="row row--flex">
    <div class="col s12 m12 l8">
        <div class="form-content">
          {% csrf_token %}
          {% form form=form %}
          {% endform %}
        </div><!-- End of form content -->
    </div><!-- End of columns -->
</div><!-- End of row -->

delivery.js

$(function () {

  var loadForm = function () {
  var btn = $(this);

  $.ajax({
    url: btn.attr("data-url"),
    type: 'get',
    dataType: 'json',
    beforeSend: function () {
      $("#modal_form").modal("open");
      console.info('%c message: Function(loadForm): Open modal', 'color: green;');
    },
    success: function (data) {
      console.info('%c message: Function(loadForm): Insert form in modal', 'color: green;');
      $("#modal_form .modal-content").html(data.html_form);
    }
  });
};

  var saveForm = function () {
  var form = $(this);
  $.ajax({
    url: form.attr("action"),
    data: form.serialize(),
    type: form.attr("method"),
    dataType: 'json',
    success: function (data) {
        if (data.form_is_valid) {
            console.info('%c message: Function(saveForm): Open modal', 'color: green;');
            $("#id_customer_container .select-dropdown").val(); // Select the customer just saved
            $("#modal_form").modal("close");
      }
      else {
          console.info('%c message: Function(saveForm): Form data is invalid', 'color: red;');
          $("#modal_form .modal-content").html(data.html_form);
      }
    }
  });
    return false;
  };

  $(".js-delivery-add-customer").click(loadForm);
  $("#modal_form").on("submit", ".js-add-customer-form", saveForm);

});

1 个答案:

答案 0 :(得分:0)

如果您的项目使用bootstrap 3或bootstrap 4,则有一个类似于admin的ForeignKey小部件,可用于添加/删除与外部相关的实例:

https://django-jinja-knockout.readthedocs.io/en/latest/widgets.html#foreignkeygridwidget

它可以适应非引导布局,但这需要额外的工作。

enter image description here