Wednesday, August 1, 2012

Re: Working with a Custom, Dynamic Form (using BaseForm)

Hi Anton,

Thank you very much for your response. The 'fields_for_a' is generating the form fields for the instance of the model 'A'. The author admits that it might not be the prettiest implementation, but fully functional. 


def fields_for_a(instance):
    # generate a sorted dict of fields corresponding to the Field model
    # for the A instance
    fields_dict = SortedDict()
    fields = field_list(instance)
    # this really, really should be refactored
    for field in fields:
        if field.field_type == Field.BOOLEAN_FIELD:
            fields_dict[field.name] = forms.BooleanField(label=field.label, required=False, help_text=field.help_text)
        elif field.field_type == Field.CHAR_FIELD:
            widget = forms.TextInput
            fields_dict[field.name] = forms.CharField(label=field.label, required=field.required, max_length=field.max_length, help_text=field.help_text, widget=widget)

.........................(etc)................

             fields_dict[field.name] = field_type(label=field.label,
                                                 required=field.required,
                                                 help_text=field.help_text,
                                                 max_length=field.max_length,
                                                 widget=widget)

    return fields_dict


I am hoping to add an additional field, "Photographers" (from the 'Photographer' model) to AForm so that users can select a Photographer to become part of an instance of the 'A' model.

Does that make sense?


Thank you very much for any ideas!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/JMg7nHwI44sJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment