如何根据django中其他下拉列表的值来过滤下拉列表的值

wlwcrazw  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(167)

我有2个模型main_category和sub_category,在sub_category模型中,它有一个名称和它所属的main_category的外键。我有第三个模型,它是'record',它有main_category和sub_category作为外键。我需要的是当从'record'表单中的下拉列表中选择主类别时,它应该过滤sub_category下拉列表中的值,以便只显示具有所选主类别的值
这些是模型

class MainCategory(models.Model):
name = models.CharField(max_length=100, unique=True)
activity_status = models.BooleanField()

def __str__(self):
    return self.name

class SubCategory(models.Model):
name = models.CharField(max_length=100)
main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE)
activity_status = models.BooleanField()

def __str__(self):
    return self.name

class Record(models.Model):
RECORD_TYPES = [
    ('income', 'Income'),
    ('expense', 'Expense'),
    ('transfer', 'Transfer'),
]

DELETED_CATEGORY = 'Deleted category'

date = models.DateField(default=timezone.now)
category = models.ForeignKey(MainCategory, on_delete=models.SET(DELETED_CATEGORY), default=1)
subcategory = models.ForeignKey(SubCategory, on_delete=models.SET(DELETED_CATEGORY))
type = models.CharField(max_length=10, choices=RECORD_TYPES)
amount = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)])
account = models.ForeignKey(Account, on_delete=models.CASCADE)
notes = models.TextField(blank=True)
transfer_ops = models.ForeignKey(TransferOperation, on_delete=models.CASCADE, null=True, blank=True)
activity_status = models.BooleanField()

def __str__(self):
    return f"{self.date} - {self.type}: {self.amount}"

这是我们的视角

class CreateRecordView(CreateView):
model = Record
form_class = RecordForm
template_name = 'create_record.html'
success_url = reverse_lazy('home')

def get_form(self, form_class=None):
    form = super().get_form(form_class)
    form.fields['subcategory'].queryset = SubCategory.objects.none()

    category_id = self.request.POST.get('category') or self.request.GET.get('category')
    if category_id:
        form.fields['subcategory'].queryset = SubCategory.objects.filter(main_category_id=category_id)

    return form

我尝试了javascript解决方案,但它不工作,这就是我所做的

{% extends 'base.html' %}

{% block content %}
<h2>Create Record</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="form-group">
  <label for="id_category">Category</label>
  {{ form.category }}
</div>
<div class="form-group">
  <label for="id_subcategory">Subcategory</label>
  <select name="subcategory" id="id_subcategory" class="form- 
control">
    <option value="">---------</option>
    {% for subcategory in subcategories %}
      <option value="{{ subcategory.pk }}" data-category="{{ 
subcategory.main_category.pk }}">{{ subcategory.name }}</option>
    {% endfor %}
  </select>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>

<script src="C:\Users\rere\PycharmProjects\bocket\js\
filter_subcategories.js"> 
</script>
{% endblock %}
$(document).ready(function() {
var subcategorySelect = $('#id_subcategory');
var subcategoryOptions = subcategorySelect.find('option');

$('#id_category').change(function() {
var selectedCategoryId = $(this).val();

// Reset subcategory options
subcategorySelect.val('');
subcategoryOptions.hide();

// Show subcategories corresponding to the selected category
subcategoryOptions.filter(function() {
  return $(this).data('category') == selectedCategoryId;
}).show();
});
});
oewdyzsn

oewdyzsn1#

我已经根据你的要求创建了一个迷你项目,你可以从这个github repo here中检查代码

浏览器输出

相关问题