Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase CharField Width in Django Forms

Tags:

django-forms

I am extending UserCreationForm and have added

username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'size':'80'}))

but the username field width does not change. How can I increase it?

like image 677
user1003121 Avatar asked Feb 17 '12 06:02

user1003121


People also ask

What is CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

What is initial in Django forms?

initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty. Let's check how to use initial in a field using a project.

How do you make a model field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.


2 Answers

Since 1.7 you can solve it like this:

admin.py

class PhotoAdmin(admin.ModelAdmin):
    list_display = (u'preview', u'caption')
    search_fields = (u'caption')
    formfield_overrides = {
        models.CharField: {'widget': TextInput(attrs={'size': '80'})}
    }
like image 61
RVE Avatar answered Oct 01 '22 03:10

RVE


Try specifying widgets in the form, as in the following example:

models.py

class Photo(models.Model):
    caption = models.CharField(max_length=80)

admin.py

class PhotoAdmin(admin.ModelAdmin):
    list_display = (u'preview', u'caption')
    search_fields = (u'caption')
    form = forms.PhotoAdminForm

forms.py

class PhotoAdminForm(forms.ModelForm):
    class Meta:
        widgets = { 'caption': forms.TextInput(attrs={'size': 80})}

As alternative, you can use the following:

forms.py

class PhotoAdminForm(forms.ModelForm):
    caption = forms.CharField(widget=forms.TextInput(attrs={'size':80}))
like image 37
Walter B Avatar answered Oct 01 '22 03:10

Walter B