Auto-generate form fields for a Form in django

后端 未结 3 1585
温柔的废话
温柔的废话 2020-12-28 22:14

I have some models and I want to generate a multi-selection form from this data. So the form would contain an entry for each category and the choices would be the skills in

相关标签:
3条回答
  • 2020-12-28 22:32

    Take a look at creating dynamic forms in Django, from b-list.org and uswaretech.com. I've had success using these examples to dynamically create form content from models.

    0 讨论(0)
  • 2020-12-28 22:39

    Okay so you can't set fields like that on forms.Form, for reasons which will become apparent when you see DeclarativeFieldsMetaclass, the metaclass of forms.Form (but not of forms.BaseForm). A solution which may be overkill in your case but an example of how dynamic form construction can be done, is something like this:

    base_fields = [
        forms.MultipleChoiceField(choices=[
            (pk, s.name) for s in c.skill_set.all()
        ]) for c in SkillCategory.objects.all()
    ]
    SkillSelectionForm = type('SkillSelectionForm', (forms.BaseForm,), {'base_fields': base_fields})
    
    0 讨论(0)
  • 2020-12-28 22:42

    What you want is a Formset. This will give you a set of rows, each of which maps to a specific Skill.

    See the Formset documentation and the page specifically on generating formsets for models.

    0 讨论(0)
提交回复
热议问题