【问题标题】:Heroku Django value too long for type character varying(20)Heroku Django 值对于类型字符变化而言太长(20)
【发布时间】:2021-03-02 23:12:06
【问题描述】:

Django 网站在开发中运行良好,但在 Heroku 上,每当我创建用户实例时都会出现此错误

django.db.utils.DataError: value too long for type character varying(20)

从 Heroku 记录错误发生在:

try:
    user = User.objects.get(phone_number=phone_number).    # It returns an error here 
except User.DoesNotExist:
    user = User.objects.create_user(
                phone_number=phone_number, username=phone_number) # Then another error here

我的用户模型如下所示:

from phonenumber_field.modelfields import PhoneNumberField

class User(AbstractUser):
    phone_number = PhoneNumberField(unique=True)
    username = models.CharField(max_length=30)
    ... bunch of other fields that are not related to the question

方法如下(邮递员):

{
    "phone_number": "+200000000000"
}

正如我所说,它在开发和 pythonanywhere 中都能完美运行。但由于某种原因,它在 Heroku 上给出了这个奇怪的错误。我可以猜测这是因为 PA 和 Dev 服务器使用的是 Sqlite3 DB,而 Heroku 使用的是 Postgres。关于如何解决这个问题的任何想法? 另外,如果使用 MySql 数据库可以解决问题,是否有关于如何使用它的文档?我是 SQL 新手,我使用的唯一 SQL 数据库是 Sqlite3

我的设置.py

try:
    import django_heroku
    django_heroku.settings(locals()).
    # for some reason when I run python3 manage.py runserver it gives me an error "django_heroku is not defined" So i had to wrap it in a try/catch block to be able to run the server in development. 
    #Please not that I ran it the server in production before without that try/catch block and it worked fine
except:
    pass

我认为这没什么用,但它是一个使用 djangorestframework 和 djangorestframework-simplejwt 的 RESTFUL API 网站

【问题讨论】:

    标签: django postgresql sqlite heroku django-models


    【解决方案1】:

    您不必创建一个名为 username 的新实例,因为 username 字段已经在 django 数据库中。因此,请在您的 Class User 中尝试以下代码:-

        user = models.OneToOneField(User, 
            on_delete=models.CASCADE,default='',unique=True)
    

    【讨论】:

    • 这不是答案,但它帮助我找到了答案,非常感谢
    • 非常欢迎您。
    • 我知道我不应该在这里问,但您知道向用户发送 SMS 消息且不按消息收费的可靠方法吗(例如每月订阅左右)?它必须是可靠的,因为我的身份验证是 WhatsApp。再次抱歉问错地方了
    • 你可以告诉我你的邮箱,我会在那里联系你。好吃吗?
    【解决方案2】:

    所以答案是......而不是使用

    user.create_user(phone_number=..., username=...)
    

    我应该使用

    user.create(phone_number=..., username=...)
    

    为什么?不知道

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2021-04-03
      • 2019-12-18
      • 2019-04-16
      • 1970-01-01
      相关资源
      最近更新 更多