Dynamically initialize a form without eval

I get data via ajax. For example, one attribute holds the Django form’s class and another holds its form data.
Now I want to initialize a form with this attribute.

I currently use “eval” for this. Its works. But that seems too dangerous to me.

Are there more suitable alternatives?

form = eval(f"{form_name_from_ajax}(form_data_from_ajax)")
if form.is_valid(): …

eval user input is really dangerous!

You can try the django’s import_string function.

1 Like

Eval on user-input is not just “really dangerous”, it’s:


(and if I could do this in red and even larger, I would)

Anyway, if you want to try and do something like this safely, you’ll want to do this “manually”. Create a dict with all the legitimate form names and form classes, and get the dict entry using the form_name_from_ajax variable.

You could even put the dict creation in the __init__.py file for the module such that the dict is created as a module-level object when the module is first imported.

(Side note - using import_string on unvalidated input can be just as dangerous depending upon what code could be run based on what happens when that module is loaded.)