Created
August 1, 2019 16:37
-
-
Save joetsoi/8158748202e5174dbf72c8daa8e71dcb to your computer and use it in GitHub Desktop.
Unlimited input for django admin with single line input widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from django.db.models import CharField | |
class CharFieldUnlimited(CharField): | |
"""Postgres specific varchar field | |
Use this over models.TextField when you want a one line input in the django | |
admin instead of the multi-line TextArea input widget. | |
Using this field gives you unlimited length CharFields, whilst still using | |
the default django (admin) widgets, so you still have a one line TextInput. | |
In postgres, if a varchar field is specified without a length, it can store | |
strings of any size, see: | |
https://www.postgresql.org/docs/8.0/datatype-character.html | |
Under the hood varchar and text in postgres are implemented as varlena, so | |
there is no difference in their implementation (apart from the length check) | |
http://www.varlena.com/varlena.php | |
https://www.depesz.com/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/ | |
https://tapoueh.org/blog/2018/04/postgresql-data-types-text-processing/ | |
""" | |
def __init__(self, *args, **kwargs): | |
# Set our default max_length to pythons sys.maxsize | |
# Since we still need a max length for the django based model and form | |
# checks, we specify sys.maxsize. This means that the | |
# autogenerated django admin forms (which have MaxLengthValidators) | |
# will continue to work. | |
defaults = {'max_length': sys.maxsize} | |
defaults.update(kwargs) | |
super().__init__(*args, **defaults) | |
def db_type(self, connection): | |
return 'varchar' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment