Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add non model field to ModelForm in Django?

I'm hoping this makes sense, here is what I want to do (for whatever reason).

I would like to create a non-model form field within my model form?

For example, below I have a model form, I would like at init to add an extra field that's not contained within the model called template. I don't save this new field so it does not need to be in my model or to I want it to be (I do some fancy ajax stuff with it.).

forms.py

class testForm(forms.ModelForm):
    def __init__(self, user=None, *args, **kwargs):
        super(testForm, self).__init__(*args, **kwargs)
        if user is not None:
            this_templates = Template.objects.for_user(user)

         self.fields["templates"] = forms.??????????
like image 381
GrantU Avatar asked Sep 06 '25 03:09

GrantU


1 Answers

You are almost there:

self.fields["templates"] = forms.CharField()

Or if you prefer another field type check the documentation for possible options.

And for additional background information take a look at Overloading Django Form Fields.

like image 116
arie Avatar answered Sep 07 '25 21:09

arie