Ibo
Ibo

Reputation: 4319

How to change the width of a drop-down field in a django form using widget attributes not css

I am trying to make all of the fields in my Django form have the same size to look tidy. I have text input, drop down and text area. I am creating the form using the Ticket model so I am not defining the form fields explicitly. I was able to resize the text input, but what is the attribute in a drop-down field that controls the width? Note that the choices in the drop-down are basically foreign keys from another table that are defined in the model.

class NewTicket(forms.ModelForm):

    class Meta:
        model=Ticket

        fields = ('subject','business','project','description')

        widgets={
            'subject': forms.TextInput(attrs={'size': '20px'}),
            'business': forms.Select(attrs={'size': '20px'}) #this line does not work
            }

Upvotes: 5

Views: 6543

Answers (2)

Will N.
Will N.

Reputation: 41

You should be able to set the widget attributes, eg. in the __init__() as

mystyle = {"style": "width:400px;", "size": 8, "rows": 8}
self.fields["something"].widget.attrs = mystyle

See here: https://docs.djangoproject.com/en/4.1/ref/forms/widgets/#django.forms.Widget.attrs

Upvotes: 2

Cyrlop
Cyrlop

Reputation: 1984

I know you said no CSS but is this an option?

class NewTicket(forms.ModelForm):

    class Meta:
        model=Ticket

        fields = ('subject','business','project','description')

        widgets={
            'subject': forms.TextInput(attrs={'style': 'width:20px'}),
            'business': forms.Select(attrs={'style': 'width:20px'})
            }

Upvotes: 12

Related Questions