[Answered ]-Django : presenting a form very different from the model and with multiple field values in a Django-ish way?

1đź‘Ť

âś…

Ok, finally I got it running by making the models closer to what I wanted to present to the user. But related to the topic of the question :

1) Nested forms/formsets are not a built-in Django feature, are a pain to implement by yourself, and are actually not needed… Rather, one should use forms’ and formsets’ prefixes.

2) Trying to work with forms not based on the models, process the data, then reinject it in the models, is much much more code than modifying the models a little bit to have nice model-based forms.
So what I did is I modified the models like that :

class PortConfig(Serializable):
    port = models.ForeignKey(Port, editable=False)
    machine = models.ForeignKey("vmm.machine", editable=False)
    is_open = models.CharField(max_length=16, default="not_open", choices=is_open_choices)

class Rule(Serializable):
    ip_source = models.CharField(max_length=24)
    port_config = models.ForeignKey(PortConfig)

Then I simply used a “model formset” for PortConfig, and “model inline formset” for Rule, with a PortConfig as foreign key, and it went perfectly

3) I used this great JS library http://code.google.com/p/django-dynamic-formset/ to put the “add field” and “delete field” links … you almost have nothing to do.

👤sebpiq

1đź‘Ť

You can create usual Forms objects by subclassing Form and adding fields in constructor, as in:

self.base_fields[field_name] = field_instance

As for the Rule, You can create a custom Field that will validate() itself according to Your rules and add it to Your custom form as above.

So Yes, it must be handmande (AFAIK), but it’s not so much code.

👤Almad

Leave a comment