GrantU
GrantU

Reputation: 6555

Only loop form values that are not blank

I loop all my items in a form. Some are my form fields are not required. If my value is blank then I don't want it to do anything.

This is what have tried to check for blank values in my for loop:

for k, v in cleaned_data.items():
            if v:
                 setattr(myModel, v, CharField())

The error I get is: '' is an invalid keyword argument for this function

Upvotes: 0

Views: 63

Answers (1)

Nicolas Cortot
Nicolas Cortot

Reputation: 6701

You cannot add fields to a model using getattr, you need to replicate the work done by the ModelBase metaclass instead:

for k, v in cleaned_data.iteritems():
    if v:
        myModel.add_to_class(v, CharField())

Upvotes: 2

Related Questions