django.db.utils.OperationalError:无法识别的令牌:“:”

问题描述 投票:0回答:1

我正在开发我的 django 项目,并且收到此错误。
最近在我删除 db.sqlite 文件并重新创建数据库后,这种情况开始发生。
在此之前它工作得很好。

这是我的代码:

def signup(req:WSGIRequest):
    form = req.POST
    if form:
        check = signup_check(req, internal=True)
        name = form.get('name')
        email = form.get('email')
        password = form.get('password')
        check = json.loads(check)
        if check['result'] == 'success':
            gender = str(form.get("gender"))
            gender = gender.lower()
            genders = ['male', 'female']
            if gender not in genders:
                gender = random.choice(genders)
            uid_hash = hasher.hash(email+name[::-2]).split("$")[-1]
            uid = utils.create_uid(uid_hash)
            try:
                new_user = User.objects.create(
                    name=name,
                    email=email,
                    gender=gender,
                    password=hasher.hash(password+email[::-2]),
                    id=uid
                )
                new_user.clean_fields()
                new_user.save()
                req.session['userinfo'] = {
                    'id' : uid,
                    'name' : name,
                    'email' : email,
                }
                return redirect('home')
            except ValidationError as e:
                err_msg = dict(e)['email'][0]
                params = {
                    'values' : {
                        'email' : email
                    },
                    'err' : err_msg
                }
                return render(req,'signup.html',params)
        else:
            params = {
                'values':{
                    'email' : email,
                    'name' : name
                },
                'err' : check['message']
            }
            return render(req,'signup.html',params)
    return render(req,"signup.html")

这是我的回溯:

Traceback (most recent call last):
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner
    response = get_response(request)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encsite\home\views.py", line 53, in signup
    new_user.save()
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\base.py", line 812, in save
    self.save_base(
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\base.py", line 863, in save_base
    updated = self._save_table(
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\base.py", line 1006, in _save_table
    results = self._do_insert(
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert
    return manager._insert(
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\query.py", line 1791, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\models\sql\compiler.py", line 1660, in execute_sql
    cursor.execute(sql, params)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\backends\utils.py", line 102, in execute
    return super().execute(sql, params)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "G:\Uranium\Programming\Web Dev\Encryptify\encryptifyenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: unrecognized token: ":"

我查找了这个问题,发现其他人也有类似的问题,但在这些情况下,他们手动编写sql查询以插入数据库。
但我正在使用 django 的模型创建一个新的 User 对象并保存它。 我使用

DEBUG=True
并在错误页面中检查了局部变量:以下是
Cursor.execute()
中使用的参数:

params  
('Tester',
 '[email protected]',
 '$argon2id$v=19$m=65536,t=3,p=4$5bGC6eTGlJfFv91ZlsBUJQ$KM6pZaHXF9ufQnrzZbnZShvmEPkTOKhuvAbDYBUOKQM',
 'male',
 None,
 None,
 'u1z6x8P1m0R5/0T373f6AuxO/ItwN+P6HKqWY837SDYhachHwkRwg')

query   
('INSERT INTO "home_user" ("name", "email", "password", "gender", "text_jobs", '
 '"image_jobs", "id") VALUES (?, ?, ?, ?, ?::integer[], ?::integer[], ?)')

self    
<django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x0000018CA457B640>

这是

User
模型:

from django.db import models
from django.contrib.postgres.fields import ArrayField

# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=150)
    password = models.CharField(max_length=97)
    gender = models.CharField(max_length=6)
    text_jobs = ArrayField(models.IntegerField(),blank=True)
    image_jobs = ArrayField(models.IntegerField(),blank=True)
    id = models.CharField(max_length=120,primary_key=True)

    def __str__(self):
        return f"{self.email} , {self.name}"
python python-3.x database sqlite django-models
1个回答
0
投票

简而言之:我通过更改 Postgres 的 sqllit3.db 解决了这个问题。

问题的原因基本上是

ArrayField
。 Sqllite3无法正确处理该字段。我没有深入挖掘来找出原因。

基本上我的模型中的这一行(我猜你的模型是因为你使用相同的ArrayField)导致了所有破坏:

ids = ArrayField(models.IntegerField(null = True,空白= True),默认=列表)

以下是有关我的模型的更多详细信息:

class UserProfile(models.Model):
    address = models.CharField(max_length=100, blank=True)
    payment_type = models.CharField(max_length=20, default="Undefined")
    total_no_of_products = models.IntegerField(default=0)
    total_paid = models.FloatField(default=0)
    ids = ArrayField(models.IntegerField(null=True, blank=True), default=list)
    user = models.OneToOneField(NewUser, on_delete=models.CASCADE, default=None)
    metadata = models.ManyToManyField(Metadata)

    def __str__(self):
       return f"{self.user.user_name}"

当我尝试在 Django shell 中保存此模型时,我得到了与您相同的错误:

错误:django.db.utils.OperationalError:无法识别的令牌:“:”

我使用的是 Django 5.0 和默认的 sqlite3 数据库,现在是 Postgres。

© www.soinside.com 2019 - 2024. All rights reserved.