Meilo
Meilo

Reputation: 3418

django: Changing auto_id of ModelForm based form class

Every time I create an instance of the TestForm specified below, I have to overwrite the standard id format with auto_id=True. How can this be done once only in the form class instead? Any hints are very welcome.

views.py

from django.forms import ModelForm
from models import Test

class TestForm(ModelForm):
    class Meta:
        model = Test

def test(request):
    form = TestForm(auto_id=True)

Upvotes: 3

Views: 1801

Answers (2)

ndpu
ndpu

Reputation: 22571

class TestForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(TestForm, self).__init__(*args, **kwargs) 
        self.auto_id = True
    class Meta:
        model = Test

Upvotes: 4

exslim
exslim

Reputation: 1146

You can override the argument in constructor:

class TestForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(TestForm, self).__init__(auto_id=True, *args, **kwargs)

Upvotes: 3

Related Questions