Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

django - value too long for type character varying(N)

My model has a SlugField. When I try to save an instance of this model with the slug field set to a string which is longer than the field's max_length parameter (which is 50 by default), I get the following error from Postgresql: value too long for type character varying(50).

Is not Django (or Postgresql) supposed to truncate the string when saving? What can I do to fix it other than truncating it manually every time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Either install south and resize the column (best option), or create a pre_save signal and add code to truncate the field to 50 characters before it is saved. Something like:

from django.db.models.signals import pre_save
from app.model import mymodel

def truncater(sender, instance, **kwargs):
    if sender is mymodel:
        if len(instance.fieldname)>50:
            instance.fieldname = instance.fieldname[:50]
pre_save.connect(truncater, sender=mymodel)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...