使用表单集在Django中的另一个下拉列表中填充下拉列表 [英] Populate dropdown list by another dropdown list in django with formsets

查看:34
本文介绍了使用表单集在Django中的另一个下拉列表中填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容,我有一个模型 Producto ,其中一个字段是另一个名为 Categoria 的模型的外键,如下所示:

I have as follows, I have a model Producto that one field is a foreign key to another model called Categoria like this:

class Categoria(models.Model):
   nombre = models.CharField(max_length=500)
   description = models.TextField(blank=True)
   imagen = models.ImageField(upload_to="/media/categorias", blank=True)

class Producto(models.Model):
   referencia = models.CharField(max_length=30)
   nombre = models.CharField(max_length=500)
   cantidad = models.IntegerField()
   precio_unidad = models.FloatField(blank=True)
   cantidad_en_pedido = models.IntegerField(blank=True)
   descatalogado = models.BooleanField(blank=True)
   proveedor = models.ForeignKey(Proveedor,related_name="proveedor",blank=True,null=True)
   categoria = models.ForeignKey(Categoria,related_name="categoria",blank=True,null=True)
   imagen = models.ImageField(upload_to="/media/productos", blank=True)

因此,当用户要下订单时,我需要为 Categoria 制作一个下拉列表,因此当用户做出选择时,另一个下拉列表将使用基于此的产品列表进行过滤类别,类似于在网络上许多网站的表单注册中针对国家和城市的下拉列表,为此,我为订单明细创建了一个模型formset_factory,其中发生了产品插入:

So, when a user wants to make an order I need to make a dropdown list for Categoriaso when the user make a choice, another dropdown list is filter with the list of products based in this category, something like dropdown list for countries and cities in a form registration of the many websites around the web, for this, I made a modelformset_factory for order detail where the insertion of product happens:

PedidoForm = modelform_factory(Pedido, exclude=("producto",),formfield_callback=make_custom_datefield)
DetallePedidoFormSet = modelformset_factory(Detalle_Pedido,exclude=("unidad_precio","pedido",), extra=1 )

这就是获取订单的视图:

And that's the view for get the order form:

def add_pedido(request):
    if request.POST:
        pedido_form = PedidoForm(request.POST, prefix='pedido')
        detalle_pedido_formset = DetallePedidoFormSet(request.POST, prefix='detalle_pedido')
        if pedido_form.is_valid() and detalle_pedido_formset.is_valid():
            pedido = pedido_form.save()
            nuevos_detalles_pedido = detalle_pedido_formset.save(commit=False)
            for nuevo_detalle_pedido in nuevos_detalles_pedido:
                nuevo_detalle_pedido.unidad_precio = nuevo_detalle_pedido.producto.precio_unidad
                nuevo_detalle_pedido.pedido = pedido
                nuevo_detalle_pedido.save()
            detalle_pedido_formset.save_m2m()
            return HttpResponseRedirect("/ventas/pedidos")
        #else:
            # form_errors = form.errors
            # return render_to_response("ventas/form.html", {'form_errors':form_errors,'form':form},
            #  context_instance=RequestContext(request))
    else:
        pedido_form = PedidoForm(prefix='pedido')
        detalle_pedido_formset = DetallePedidoFormSet(queryset=Detalle_Pedido.objects.none(),prefix='detalle_pedido') # or give a different initial queryset if you want some preselected choice
    extra_context = {'form_pedido': pedido_form, 'detalle_pedido_formset': detalle_pedido_formset}
    return render_to_response("ventas/form_pedido.html", extra_context,
             context_instance=RequestContext(request))

如何在我的表单集中定义它,许多站点建议做一个 ModelChoiceField ,但是我不知道如何为表单集定义任何想法?

How could define this in my formsets, many sites suggest of doing a ModelChoiceFieldbut I don't know how to define for a formset, any ideas?

致谢!

推荐答案

我遇到了一个类似的问题,该问题与基于用户选择(可以是表中的多行)在表单集中填充下拉菜单有关.对我有用的是在将所选行放入表单集中之前修改表单集中的base_fields,如下所示:

I had a similar problem related to populating drop down menus in a formset based on a user selection (which could be multiple rows in a table). What worked for me was to modify the base_fields in the formset before I put the selected rows in the formset like so:

formset = modelformset_factory(mymodel)

formset.form.base_fields['my_parameter'] = forms.ChoiceField(choices=getMyParamChoices())

finalformset = formset(queryset=model.objects.filter(id__in=request.POST.getlist('selection')

选择"是上一页中选定行的列表.

'selection' is the list of selected rows from the previous page.

getMyParamChoices()是一个查询模型以获取下拉选项列表的函数,如下所示:

getMyParamChoices() is a function that queries a model to get the list of pulldown choices like so:

def getMyParamChoices():
'''Go get the list of names for the drop down list.'''
all = anothermodel.objects.all()
params = []
for item in all:    
    new1 = (item.name,item.name)
    params.append(new1)

return(tuple(params))

ChoiceField需要一个元组才能正常工作,并且name是下拉列表中我想要的值.

ChoiceField requires a tuple in order to work properly and name is the value I want in the drop down.

我希望这会有所帮助.如果您希望下拉菜单在客户端动态更改,则需要编写一些JavaScript来填充下拉菜单.

I hope this helps. If you want the pull-down to dynamically change on the client side, then you'll need to write some JavaScript to populate the drop down menus.

这篇关于使用表单集在Django中的另一个下拉列表中填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆