0

In a custom ModelForm, I would like to have a HiddenInput field which has the value of the Autofield primary key of the model. If the form is created without a model, then this field would be None. If a model is provided to instantiate the form, it should contain the Autofield ID of the model. Is this possible? I am thinking something like this:

class MyCustomForm(forms.ModelForm):
    the_id = forms.HiddenInput()

    def __init__(self, *args, **kwargs):
        super(MyCustomForm, self).__init__(*args, **kwargs)
        self.fields["the_id"].initial = args.get('id', None)
emispowder
  • 1,787
  • 19
  • 21

1 Answers1

1

So after digging around I came across this:

https://groups.google.com/forum/?fromgroups=#!topic/django-users/vmIXXr5tsdI

Which points out that there is no HiddenInput field for ModelForms. I should have read the docs more closely. Here is what I have in the end:

MyCustomForm(forms.ModelForm):
    the_id = forms.IntegerField(widget=forms.HiddenInput)

    def __init__(self, *args, **kwargs):
        super(MyCustomForm, self).__init__(*args, **kwargs)

        instance = getattr(self, 'instance', None)
        if instance and instance.id:
            self.fields["the_id"].initial = instance.id
emispowder
  • 1,787
  • 19
  • 21