diCoy
diCoy

Reputation: 79

django formfield_overrides conflicts with max_length in TextField

So I have a model where one of the fields goes like this:

dirlab_cruce = models.CharField(verbose_name='Cruce', max_length=40, null=True, blank=True)

To be able to have all the textfields in the same length i did this in admin.py:

formfield_overrides = {
    models.CharField: {'widget': TextInput(attrs={'size':'100%'})}
}

This made all the textfields tha same width as the form, but limits the text I can input to 4 characters.

Commenting the formfield_overrides block gives me a 40 character input like I wanted, the it shortens the charfield.

Am I doing something wrong?

Thanks

Upvotes: 3

Views: 1363

Answers (1)

Joe Golton
Joe Golton

Reputation: 632

I had the same issue. It's a Django 1.4 bug, so I just filed a report. Here's the ticket I filed, with an easy way to recreate the bug:

title: using formfield_overrides to set CharField size causes all admin fields to use last max_length in model definition

description: See how title and ISBN are defined with max_length of 100 and 14. The override cause both fields to have max_length of 14 with respect to a user who is editing in the change form - a 15th character cannot be inserted into the title field.

models.py:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100,blank=True, null=True)
    ISBN13 = models.CharField(max_length=14,unique=True)
    def __unicode__(self):
        return self.title

admin.py:

from django.contrib import admin
from django.db import models
from django.forms import TextInput
from books.models import Book

class BookAdmin(admin.ModelAdmin):
    formfield_overrides = {
        # Django enforces maximum field length of 14 onto 'title' field when user is editing in the change form
        models.CharField: {'widget': TextInput(attrs={'size':'30'})},
        }

admin.site.register(Book,BookAdmin)

EDIT: Within 48 hours of my bug submission, the amazing Django community verified the bug and issued a patch. I tested and confirmed that this bug was fixed in Django 1.5, which was released in March, 2013.

https://code.djangoproject.com/ticket/19423#ticket

Upvotes: 4

Related Questions