3

I have model:

class TestPolja(models.Model):
    class Meta:
        verbose_name = 'Test polja'

        integerPolje1 = models.IntegerField('integerPolje1')
        charPolje1 = models.CharField('charPolje1',max_length = 1024)
        bigint1 = models.BigIntegerField('bigint1',default = 67573737)
        date = models.DateField('date')

and modelForm:

class TestPoljaForm(ModelForm):
    class Meta:
        model = TestPolja

How to change TestPoljaForm to add class attribute to <input> tag?

How to add widget?

2 Answers 2

5

You can do it in __init__ form method:

class TestPoljaForm(ModelForm):
    class Meta:
        model = TestPolja

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

        # for example change class for integerPolje1
        self.fields['integerPolje1'].widget.attrs['class'] = 'SOMECLASS'

        # you can iterate all fields here
        for fname, f in self.fields.items():
            f.widget.attrs['class'] = 'SOMECLASS'
Sign up to request clarification or add additional context in comments.

2 Comments

And for each field i must iterate trough all fields and add widget?
Thank you. This took effect for me. You could use self.fields.values() instead of .items()
3
class TestPoljaForm(ModelForm):
    integerPolje1 =  forms.IntegerField(widget=forms.TextInput(attrs={'class': 'myclass'}))

    class Meta:
        model = TestPolja

3 Comments

I would prefer this method.
This is ok too, but i want to set the same class name to all fields.
I wonder if it is possible to add classes in dict notation. I tried attrs=dict(class='my_class') but this obviously did not work, since Django (i.e. Python) was expecting a class declaration after class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.