首页 > 解决方案 > Django“adminlike”外键添加按钮

问题描述

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

我已经阅读了此处显示的自定义小部件上的线程:Django:在 ModelForm 中为 ForeignKey 添加“添加新”按钮 不幸的是我无法让它工作,所以我尝试了一种不同的方法。

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

所以我得到了表格,它在不离开交付表格区域的情况下向数据库添加了一个新客户。诀窍是,我想在客户下拉列表中选择新添加的客户。

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

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

网址.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'),
]

视图.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 -->

交付.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);

});

标签: jqueryajaxdjango

解决方案


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

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

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

在此处输入图像描述


推荐阅读