[Django]-Django – Changing inline formset textInput size attribute

7👍

EDIT: It should probably just set a class to the input field and have the CSS assign the width. That way you could pass it to separate templates and such for different clients.

Perhaps instead of using .attrs['size'] = 30 use .attrs['class'] = 'some_class' then define the class in your HTML template and handle the different sizes there.

This should work:

class Product_Form(ModelForm):
    def __init__(self, *args, **kwargs):
        super(Product_Form, self).__init__(*args, **kwargs)
        self.fields['qty'].widget.attrs['size'] = 30

    class Meta:
        model = Estimate_Product_Details
        fields = ('CID', 'qty')

3👍

I also had problems with @Furbeenator’s code. However, on checking the resulting HTML, I found the size attribute was being appended to the <input> tag correctly.

The problem: I was using a third-party template which was overriding the <input> width with its own CSS definition.

The solution is to pass the width as a style attribute rather than size:

class UserProfileForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        self.fields['company'].widget.attrs['style'] = "width:500px"

This modification also works for @Furbeenator’s View modification. I did not try the JQuery variant (although the template uses JQuery, I’m not at the moment).

The only downside is that the field width is now defined in terms of CSS units such as pixels or em/ex. I’m going to switch to ex, but it would be nice if CSS had an “average character width” unit so that you can define boxes like this to “hold 20 chars”,etc.

0👍

It is also possible to add a css class name for each input of form. To do it you should add widget attr to your definition of form input. Like bellow:

field_name = forms.CharField(label='label', max_length=100, widget=forms.TextInput(attrs={'class':'input-control'}))

Leave a comment