2016-01-13 42 views
0

我有一个模型在一个字段中存储不同类型的数据(离散值或连续值)(在另一个字段中存储类型)。在该模型的ModelForm中,我有一个ChoiceField来选择数据项,并使用ChoiceField或DecimalField来设置项目的值。在django管理员表单中响应用户操作?

当我创建表单时,我根据项目的类型设置值的字段。但是,如果我选择不同类型的项目,我想立即更改值字段以匹配。

当窗体仍处于活动状态时,即在用户更改字段值但未单击“提交”按钮时,我无法找到任何方式来响应更改。有没有办法做到这一点?最好留在服务器上的Python,而不是浏览器端在javascript中编码。

ChoiceField的选项取自模型,因此无法在任何地方进行硬编码。

下面是一些代码:

class FooProperty (models.Model): 
    foo  = models.ForeignKey ('foos.Foo') 
    prop = models.ForeignKey ('foos.FooProperty') 
    value = models.DecimalField (max_digits=15, decimal_places=6) # is an EnumValue id in the case of discrete values. 

class FooPropertyForm (forms.ModelForm): 
    class Meta: 
     model = FooProperty 
     fields = ['prop', 'value'] 

    def __init__(self, *args, **kwargs): 
     super (FooPropertyForm, self).__init__(*args, **kwargs) 

     if hasattr (self.instance, 'prop'): 
      kind = self.instance.prop.units.kind 
      if kind.id != 1: 
       values = [(v.id, v.name) for v in EnumValues.objects.filter (kind=kind.id)] 
       self.fields ['value'] = forms.ChoiceField (choices=values, required=True) 
       self.initial['value'] = int(self.instance.value) # using initial= above doesn't work. 
      else: 
       # keep the default field. 
       pass 

回答

0

我具有存储不同类型的值(STR,INT,小数,等),根据其类型相似的多态模型。

你能澄清一下你的问题吗?你说“如果我选择一个不同类型的项目”。你的意思是改变浏览器或代码中的表单域?

我假设你是指前者。 如果没有来自客户端的某种异步通信,则无法响应Python中的实时表单更改。

在我的应用程序,这是一个两步骤的过程:

  1. 来选择一个类型
  2. 在客户端的用户,该类型字段的改变处理器触发调用来获取类型 - 特定的表单字段。有一个单独的Django视图,它用一组特定的字段和逻辑来实例化一个单独的表单。

var $kind = $('#kind'); 
 

 
$kind.on('change', fetchFormFieldsForKind); 
 

 
function fetchFormFieldsForKind() { 
 
    var kind = $kind.val(); 
 
    $.get(
 
    "{% url 'form_fields_for_kind' %}?kind=" + $kind.val(), 
 

 
    function (response) { 
 
     newFieldsHtml = response.newFieldsHtml || ''; 
 

 
     // Replace all following sibling form fields with the new ones 
 
     // (each field is wrapped by a div with Bootstrap class form-group) 
 
     $kind.closest('.form-group').find('~ .form-group').remove(); 
 
     $kind.after(newFieldsHtml); 
 

 
     // or replace the whole form with a rendered ModelForm 
 
    } 
 
); 
 
}

对于完整性,即Django的看法会是这个样子:

def form_fields_for_kind(request, kind): 
    """ 
    Given the string 'kind', return a rendered form that contains 
    any type-specific fields. 
    """ 
    form = YourForm(kind=kind) 
    content = form.as_p() 
    return HttpResponse(content, 'text/html') 
相关问题