python – Reload forms.ModelForm

Question:

I have a form for the admin panel:

class PermissionModelForm(forms.ModelForm):
  queryset = MyGroup.objects.all()
  for group_object in queryset:
    exec('group_{0} = forms.BooleanField()'.format(group_object.group_name))

  class Meta:
    model = MyPermission
    fields = ('permission_name', 'permission_description')

In it, the fields are set according to the available groups. The problem is that they are created during server startup. How do I reload the form, say after adding / removing / editing a group? Group shape:

class GroupModelForm(forms.ModelForm):
  class Meta:
    model = MyGroup
    fields = ('group_name', 'group_tag')

  def save(self, commit=True):
    group = super(GroupnModelForm, self).save(commit=False)
    if commit:
      group.save()
    return group

Answer:

It is more correct in this case to create fields dynamically in the __init__ method:

class PermissionModelForm(forms.Form):
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for group_object in MyGroup.objects.all():
            self.fields['group_{}'.format(group_object.group_name))] = forms.BooleanField()
Scroll to Top
AllEscort