2017-08-24 86 views
1

我得到的波紋管錯誤:__init __()得到了一個意想不到的關鍵字參數 'MIN_LENGTH'

... 
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper 
    fn(*args, **kwargs) 
    File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/__init__.py", line 27, in setup 
    apps.populate(settings.INSTALLED_APPS) 
    File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/registry.py", line 108, in populate 
    app_config.import_models() 
    File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/config.py", line 202, in import_models 
    self.models_module = import_module(models_module_name) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module 
    __import__(name) 
    File "/Users/luowensheng/Desktop/QIYUN/Project/officialWeb/frontend/models.py", line 93, in <module> 
    class User(models.Model): 
    File "/Users/luowensheng/Desktop/QIYUN/Project/officialWeb/frontend/models.py", line 97, in User 
    phone = models.CharField(min_length=11, max_length=11) 
    File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/db/models/fields/__init__.py", line 1061, in __init__ 
    super(CharField, self).__init__(*args, **kwargs) 
TypeError: __init__() got an unexpected keyword argument 'min_length' 

我的模型代碼如下:

class User(models.Model): 
    username = models.CharField(max_length=16) 
    password = models.CharField(max_length=16) 
    real_name = models.CharField(max_length=12) 
    phone = models.CharField(min_length=11, max_length=11) # this is the line 97 
    email = models.EmailField() 
    qq = models.CharField(max_length=10) 
    address = models.CharField(max_length=64) 
    id_card = models.CharField(min_length = 18, max_length=18) 
    id_card_img_front = models.CharField(max_length=256) 
    id_card_img_back = models.CharField(max_length=256) 
    nickname = models.CharField(max_length=16) 
    profile = models.CharField(max_length=256) 

爲什麼我得到這個錯誤? 順便說一下,如果有更好的方法來限制電話長度11

回答

1

由於錯誤提示,CharField沒有min_length選項。您可以使用MinLengthValidator代替

from django.core.validators import MinLengthValidator 

class User(models.Model): 
    phone = models.CharField(max_length=11, validators=MinLengthValidator(11)) 
+0

謝謝,順便問一下,是否有更好的方法來將CharField長度限制爲「11」? – aircraft

+0

@aircraft固定長度,你可以在這裏閱讀更多https://stackoverflow.com/questions/2470760/django-charfield-with-fixed-length-how –

+0

這是我能想到的最簡單的方式。既然你想要的長度是11,你可以[寫你自己的驗證器](https://docs.djangoproject.com/en/1.11/ref/validators/#writing-validators)與一個更具體的錯誤消息。 – Alasdair

1

CharField數據庫模型字段實例只有一個MAX_LENGTH參數。這可能是因爲SQL中只有最大字符長度限制。

from django.core.validators import RegexValidator 

class User(models.Model): 
    phone = models.CharField(validators=[RegexValidator(regex='^.{11}$', message='Length has to be 11', code='nomatch')]) 
相關問題