emispowder
emispowder

Reputation: 1797

How to have an Autofield value of a model as a custom ModelForm field

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)

Upvotes: 0

Views: 1045

Answers (1)

emispowder
emispowder

Reputation: 1797

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

Upvotes: 1

Related Questions