Django数值错误,解包值不足(期望4个,实际2个)。

huangapple go评论61阅读模式
英文:

Django ValueError, not enough values to unpack (expacted 4, got 2)

问题

我想要将我的数据库从sqlite3更改为mysql,但每次这样做时,无论我尝试从数据库检索数据时都会遇到错误:

Django数值错误,解包值不足(期望4个,实际2个)。

即使我尝试登录到管理员面板,我也会遇到相同的错误!(createsuperuser正常工作):
Django数值错误,解包值不足(期望4个,实际2个)。

这是我的模型:

class Website(models.Model):
    # ...

class Data(models.Model):
    # ...

class CustomUser(AbstractUser):
    # ...

class Claps(models.Model):
    # ...

class Fav(models.Model):
    # ...

这是我的序列化器:

from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Data, CustomUser

class UserSerializer(serializers.ModelSerializer):
    # ...

class DataSerializer(serializers.ModelSerializer):
    # ...

这是我的manager.py:

from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    # ...

也许与models.ManyToManyfield有关。我有一个急切等待Web应用程序的客户。请花点时间解决我的问题!

英文:

I want to change my database from sqlite3 to mysql, but every time I do so, I encounter an error whenever I try to retrieve data from the database:

Django数值错误,解包值不足(期望4个,实际2个)。

Even when I try to log in to admin panel, I get the same error! (createsuperuser works fine):
Django数值错误,解包值不足(期望4个,实际2个)。

Here are my models:

class Website(models.Model):
    name = models.CharField(max_length=500)
    URL = models.CharField(max_length=500)
    Logo = models.CharField(max_length=1000,null=True,blank=True)

class Data(models.Model):
    website = models.ForeignKey(Website, on_delete=models.CASCADE , null=True, blank=True)
    Target_website= models.CharField(max_length=500,null=True,blank=True)
    URL = models.CharField(max_length=500,null=True,blank=True)
    Title = models.CharField(max_length=1000, unique=True)
    Description = models.TextField(null=True,blank=True)
    Keywords = models.TextField( null=True,blank=True)
    Text = models.TextField(    null=True,blank=True)
    Links = models.TextField(  null=True,blank=True)
    Images = models.TextField(  null=True,blank=True)
    Videos = models.TextField(  null=True,blank=True)
    Claps = models.IntegerField(default=0)
    TimeStamp = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.Title

    def change_claps(self, x):
        self.Claps += x
        self.save()



class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=14)
    last_name = models.CharField(max_length=14)
    password = models.CharField(max_length=20)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now_add=True) #auto_now = True if you want to add a field like "updated_on"
    favourite_posts = models.ManyToManyField(Data, blank=True, null=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()


class Claps(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_likes')
    data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_likes')


class Fav(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_favs')
    data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_favs')

Here are my serializers:

from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Data, CustomUser

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        # fields = ('id', 'username', 'email', 'password')
        # extra_kwargs = {'password': {'write_only': True}
        fields = "__all__"


class DataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Data
        fields = "__all__"

Here is my manager.py:

from django.contrib.auth.base_user import BaseUserManager


class UserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, password=None, **extra_fields):
        print("creating user")
        if not email:
            raise ValueError("Email not provided!")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('SuperUser must have is_staff true!')

        return self.create_user(email, password, **extra_fields)

Maybe it has to do something with the models.ManyToManyfield. I have a client that is impatiently waiting for the web app. Please take some time to solve my problem!

答案1

得分: 1

保持简单,倾向于使用以下步骤。

转储现有数据:

python manage.py dumpdata -e sessions --natural-foreign --natural-primary > data.json

然后在settings.py中切换DATABASES设置:

python manage.py migrate #设置数据库结构
python manage.py loaddata data.json #导入数据

在转储中使用的--natural-foreign--natural-primary选项应有助于保留关系。

英文:

I would keep it simple if you can.

Dump your existing data:

python manage.py dumpdata -e sessions --natural-foreign --natural-primary > data.json

Then switch your DATABASES setting in in settings.py

python manage.py migrate #sets up database structure
python manage.py loaddata data.json #imports your data

The --natural-foreign and --natual-primary options in the dump should help you preserve the relations.

答案2

得分: 0

感谢 Zemogle,但我找到解决方案。

备份您的数据(以防万一),只需将密码字段的最大长度增加到类似 200 的值。请注意,与低密码长度创建的用户相关的所有操作都将出现相同的错误。

class CustomUser(AbstractUser):
    ....
    password = models.CharField(max_length=200)
    ....

这个解决方案在整个互联网上都找不到,请在您能够传播的任何地方分享这个简单但有效的解决方案。我花了几天的时间才找到问题。

英文:

Thank you Zemogle but I found the solution.

backup your data, (just in case) and just increase the max_length of the password field to something like 200. Note that all operations related to the users who were created with the low password length will give the same error.

class CustomUser(AbstractUser):
    ....
    password = models.CharField(max_length=200)
    ....

This solution is no where on the WHOLE INTERNET so please spread this simple but effective solution everywhere you can. It took me days of grinding to find the problem.

huangapple
  • 本文由 发表于 2023年4月6日 18:58:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75948720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定