Reputation: 533
I have a form with two modelchoice fields to filter a line chart The first modelchoicefield is filled with a list of providers
The second modelchoicefield must load a list of products of the selected provider models:
class Proveedor(models.Model):
id_proveedor = models.AutoField(primary_key = True)
nombre = models.CharField(max_length=150,blank=False,null=False)
codigo_asignado = models.CharField(max_length=50,blank=False,null=False)
id_servicio = models.ForeignKey(Servicio,db_column='id_servicio',verbose_name='Servicio')
class Meta:
verbose_name_plural = "Proveedor"
def __unicode__(self):
return self.nombre
class Product(models.Model):
id_lista = models.IntegerField(primary_key=True)
fecha = models.CharField(max_length=12)
id_prov = models.ForeignKey(Proveedor,db_column='id_proveedor', verbose_name='Proveedor')
corto = models.CharField(max_length=15)
conteo = models.IntegerField()
dia = models.CharField(max_length=24)
class Meta:
managed=False
db_table='pc_v_stat_corto'
def __unicode__(self):
return self.corto
Form:
class ChartCCForm(forms.Form):
provider = forms.ModelChoiceField(queryset=Proveedor.objects.all().order_by('nombre'),label='Proveedor')
product = forms.ModelChoiceField(queryset=STAT_CORTO.objects.all(),to_field_name="corto",required=True)
def __init__(self,*args, **kwargs):
super(ChartCCForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
my view
def StatCortoView(request):
formulario = ChartCCForm()
prov = request.POST.get('id_proveedor')
codigo = request.POST.get('codigo')
mes = request.GET.get('mes')
try:
prov = prov
codigo = codigo
mes = mes
except ValueError:
prov = None
codigo = None
mes = None
query = STAT_CORTO.objects.filter(id_prov=prov).filter(corto=codigo)
ds = DataPool(
series=
[{'options': {
'source': query},
'terms': [
'dia',
'conteo']}
])
cht = Chart(
datasource = ds,
series_options =
[{'options':{
'type': 'line',
'stacking': False},
'terms':{
'dia': [
'conteo']
}}],
chart_options =
{'title': {
'text': 'Codigos Cortos por Dia'},
'xAxis': {
'title': {
'text': 'Fecha'}}})
return render(request,'chartcc.html',
{'grafico':cht,'form':formulario})
how can I update the product modelchoicefield based in the selected provider
thanks in advance
Upvotes: 2
Views: 537
Reputation: 136
What you are wanting isn't really possible using Django forms. The forms will only provide the choices it has when it is made, so you will have to product queryset all your possible products, and then filter them on the frontend using javascript.
See here: conditional/contingent model field choices
Upvotes: 1