I’m building a Django site. I need to model many different product categories such as TV, laptops, women’s apparel, men’s shoes, etc.
Since different product categories have different product attributes, each category has its own separate Model: TV, Laptop, WomensApparel, MensShoes, etc.
And for each Model I created a ModelForm. Hence I have TVForm, LaptopForm, WomensApparelForm, MensShoesForm, etc.
Users can enter product details by selecting a product category through multi-level drop-down boxes. Once a user has selected a product category, I need to display the corresponding product form.
The obvious way to do this is to use a giant if-elif structure:
# category is the product category selected by the user
if category == "TV":
form = TVForm()
elif category == "Laptop":
form = LaptopForm()
elif category == "WomensApparel":
form = WomensApparelForm()
...
Unfortunately there could be hundreds if not more of categories. So the above method is going to be error-prone and tedious.
Is there any way I could use the value of the variable category to directly select and initialize the appropriate ModelForm without resorting to a giant if-elif statement?
Something like:
# This doesn't work
model_form_name = category + "Form"
form = model_form_name()
Is there any way to do this?
If all your
*Formclasses are in the one module (let’s call itforms), you can do this:(Obviously, add whatever verification is necessary, such as catching
AttributeError. Security-wise, if you are using a named module rather than the global namespace, it’s that little bit harder for someone to inject a new*Formclass.)