Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Adding fields dynamically to a fieldset #11

Closed
gergelypolonkai opened this issue Feb 16, 2015 · 1 comment
Closed

[Question] Adding fields dynamically to a fieldset #11

gergelypolonkai opened this issue Feb 16, 2015 · 1 comment

Comments

@gergelypolonkai
Copy link

Hello,

I’m trying to create a form with dynamically created fields, adding those fields to field sets depending on some conditions. By inspecting the library code I was trying like this:

class BuildCreateForm(BetterForm):
    description = forms.CharField(label = 'Description')

    def __init__(self, *args, **kwargs):
        product = kwargs.pop('product')

        super(BuildCreateForm, self).__init__(*args, **kwargs)

        for field in product.fields.all():
            field_id = 'field_%s' % field.pk
            self.fields[field_id] = forms.CharField(
                label = field.name,
                required = False)
            self.Meta.fieldsets[0][1]['fields'].append(field_id)

    class Meta:
        fieldsets = [('build_fields', {
            'fields': [],
            'legend': 'Fields'})]

which obviously fails, as adding something to Meta multiple times will be reflected in all instances (ie. refreshing my test page will display one more of the dynamic field after each refresh). As Fieldset has no method to add a field, I was wondering if it is actually possible.

Thanks in advance!

Best,
Gergely

@carljm
Copy link
Owner

carljm commented Feb 16, 2015

It's certainly possible, but it's not public API. The metaclass copies the fieldsets from the Meta inner class to the base_fieldsets class attribute on class creation, and then in BetterForm.__init__ the base_fieldsets are copied to the self._fieldsets instance attribute. So it's the latter you'd want to modify in order to tweak just the one form instance.

@carljm carljm closed this as completed Feb 16, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants