2

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.??????????
Pradeep Sapkota
  • 2,041
  • 1
  • 16
  • 30
GrantU
  • 6,325
  • 16
  • 59
  • 89

1 Answers1

5

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.

arie
  • 18,737
  • 5
  • 70
  • 76
  • Ok cool somehting like this then.... self.fields["templates"] = forms.ChoiceField(queryset=this_templates) however this gives an error: __init__() got an unexpected keyword argument 'queryset' – GrantU May 19 '13 at 16:11
  • 1
    A ```ChoiceField``` is not a ```ModelChoiceField```. It doesn't take a ```queryset``` but a ```choices``` argument. Check this for example: http://stackoverflow.com/a/3420588/630877 – arie May 19 '13 at 16:14