如何在具有多个字段的Django中实现链式下拉列表?

时间:2019-09-16 08:14:17

标签: python django django-models django-forms django-views

我为模型(工具箱)创建了一个表单,该表单由两个不同的模型通过外键和manytomany字段连接。现在,我希望表单在选择一个选项后立即自动在表单字段中预填充数据。这是我的代码。

代码

models.py

# Parent model connected with both models
class Kit(models.Model):
    kit_name = models.CharField(max_length=255, default=0)
    kit_info = models.CharField(max_length=255, default=0)
    components_per_kit = models.IntegerField(default=0)
    product_id = models.ManyToManyField(Product, related_name='kit_product')
    quantity_per_kit = models.IntegerField(default=0)
    kit_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='kit_owner')

# connected by foreign key
class Client(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    client_company = models.CharField(max_length=255, default=0)
    client_name = models.CharField(max_length=255, default=0)

# connected by many to many field
class Product(models.Model):
    product_id = models.IntegerField(default=0)
    product_name = models.CharField(max_length=255, default=0)
    product_short_code = models.CharField(max_length=255, default=0)
    product_description = models.CharField(max_length=255, default=0)

模板:

{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <h2 class="mb-3">Add a new Kit</h2>
  <div class="row">
    <div class="col-md-6 col-sm-8 col-12">
      <form method="post" novalidate>
        {% csrf_token %}
        {{ form|crispy }}
        <button type="submit" class="btn btn-success">Save</button>
        <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a>
      </form>
    </div>
  </div>
{% endblock %}

我遵循了本指南How to Implement Dependent/Chained Dropdown List with Django,并且我想扩展它以填充很多字段,而不仅仅是下拉列表。这可能吗 ?我应该怎么做?

0 个答案:

没有答案