Formset with per field widget selection
I am making a front end for custom testing framework. Each test has some associated scripts and each script has some associated parameters and each parameter has a parameter type. I want to be able to create a form to edit all of the parameters for a given test and have each of the fields display and validate according to the associated parameter type, ie if the parameter type is 'bool' the input should be a checkbox, if the type is a url it should validate appropriately.
models.py:
...
PARAM_TYPES = (('bool', 'Boolean (Flag Only)'),
('int', 'Integer'),
('ip', 'IP Address'),
('txt', 'Text'),
('url', 'url'),
开发者_开发知识库 ('path', 'File Path'))
class Parameter(models.Model):
name = models.CharField(max_length=50)
flag = models.CharField(max_length=20)
type = models.CharField(max_length=20, choices=PARAM_TYPES)
description = models.TextField(max_length=200)
...
class ParameterInstance(models.Model):
parameter = models.ForeignKey(Parameter)
value = models.CharField(max_length=50, blank=True)
...
class ScriptInstance(models.Model):
name = models.CharField(max_length=50)
test = models.ForeignKey(Test) # One node may have many ScriptIntances (OneToMany)
script = models.ForeignKey(Script) # Many ScriptInstances to one Script (ManyToOne)
parameter_instances = models.ManyToManyField(ParameterInstance, blank=True)
...
...
Currently my views.py is repackaging the the parameter types, parameter instance id and value information and I am rendering different inputs in my template based on the type. And then using request.POST.getlist() to get the info back into the appropriate records.
It seems to me there should be a way to cause the forms in a formset to pick a widget based on the type. Or something else better than my current way.
精彩评论