Django populate Model form dynamically with model - possible?
I am trying to use a model form independently of the model that is passed. My goal is to have a list of database tables where the user can select the table which is then displayed. Then within this table there is the possibility to select a table entry which can be updated. There will be changing tables over time, therefore I want to use one model form to include all the fields for editing and just change the underlying Model.
I tried some things and right now this is my "last" attempt that is not working. Any advice or guidance?
This is in my views.py
class DynamicModelForm(forms.ModelForm):
class Meta:
model = None
fields = '__all__'
# setting the model based on the input selection of user
def get_dynamic_form(request, model, instance=None):
DynamicModelForm.model = model
DynamicModelForm.fields = '__all__'
return DynamicModelForm(request.POST or None , instance=instance)
#
#
#
# in my class based view I am using this to list the tables
def list(self, request, model, model_name):
print(f'Pulling model {model_name}')
objects = model.objects.all()
fields = [field.name for field in model._meta.fields] # Retrieve field names
self.context['fields'] = fields
self.context['model_name'] = model_name
self.context['objects'], self.context['info'] = set_pagination(request, objects)
if not self.context['objects']:
return False, self.context['info']
return self.context, 'app/transactions/table_view.html'
Your get_dynamic_form
, is essentially what Django does with a modelform_factory(…)
[Django-doc]. Indeed, we can thus work with:
from django.forms.models import modelform_factory
def get_dynamic_form(request, model, instance=None):
return modelform_factory(model, fields='__all__')(
request.POST or None, instance=instance
)