我有两个下拉菜单:
两者都需要动态填充
在这里,我想根据从类别字段中选择的值填充sub_category中的选择。 所以我不需要保存整个表格。
class AddProductForm(forms.Form):
category = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}),
queryset=Category.objects.all(), to_field_name="category")
sub_category = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}))
答案 0 :(得分:0)
带有django_select2的示例
models.py
from django.db import models
class Category(models.Model):
name_category = models.CharField(verbose_name='Category title', max_length=100, null=True)
slug = models.SlugField(max_length=160, unique=True, null=True)
class Meta:
ordering = ('name_category',)
def __str__(self):
return self.name_category
class Subcategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Category', related_name='sub')
name_subcategory = models.CharField(verbose_name='Subcategory title', max_length=100, null=True)
slug = models.SlugField(max_length=160, unique=True, null=True)
class Meta:
ordering = ('category', 'name_subcategory',)
def __str__(self):
return self.name_subcategory
class Product(models.Model):
subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, verbose_name='Category', related_name='prod')
name_product = models.CharField(verbose_name='Product title', max_length=100, null=True)
price = models.IntegerField(verbose_name='Price')
class Meta:
ordering = ('name_product', )
def __str__(self):
return self.name_product
forms.py
(我使用了'style':'width:350px;',因为我在此测试项目中没有任何CSS)
from django import forms
from django_select2.forms import ModelSelect2Widget
from .models import Category, Subcategory
class AddProductForm(forms.Form):
category = forms.ModelChoiceField(
queryset=Category.objects.all(),
widget=ModelSelect2Widget(
search_fields=['name_category__icontains'],
attrs={'style': 'width:350px;', },
)
)
sub_category = forms.ModelChoiceField(
widget=ModelSelect2Widget(
attrs={'style': 'width:350px;', },
model=Subcategory,
search_fields=['name_subcategory__icontains'],
dependent_fields={'category': 'category'},
),
queryset=Subcategory.objects.all(),
)
views.py
from .forms import AddProductForm
class AddProductView(FormView):
form_class = AddProductForm
template_name = "categories/new_product.html"
new_product.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="PATH_TO_JQUERY"></script>
{{ form.media }}
</head>
<body style="background-color: white;">
<form>
<table>
{{ form.as_table }}
</table>
</form>
</body>
</html>
您还需要将path('select2/', include('django_select2.urls')),
中的urls.py
放入'django_select2'
中,INSTALLED_APPS
放入您的settings.py
中
还要提及的另一件事是,依赖字段仅在一种表单内起作用,并且form
标签是强制性的