I'm trying to create generic views for my models and I'm stuck at creating a modelform dynamically. It's there a way of creating a modelform just by having the model's name as string?
You could do this by simply defining the class for the model form in the view's local scope and then create an instance of it directly after. You just need to make sure you receive the class of the model according to its name. Use django's get_model
function. Simple example:
def my_view(request):
model_name = "myapp.MyModel" #make sure the app name is also provided
from django.db.models import get_model
model_class = get_model(*model_name.split('.'))
class MyModelForm(ModelForm):
class Meta:
model = model_class
# other attributes of the form
form = MyModelForm()
# ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.