草庐IT

python - Django:调用 user.objects.get() 时为 "Too many values to unpack"

coder 2023-08-15 原文

在 Django 1.6 中,我定义了一个自定义用户模型,但出于某种原因,现在当我创建一个 super 用户并尝试获取它或以该 super 用户身份访问 Django 管理员时,我得到了这个 ValueError: Too many要解压的值。我仔细阅读了关于此错误的许多类似问题,但没有找到适合我的特定问题的任何内容。我不知道会出什么问题。

在自定义管理器中的自定义 create_usercreate_superuser 方法中,我确实传递了一个额外的字段,但该字段实际上并没有进入模型,所以我看不出为什么会导致问题。

此外,当尝试访问管理员时,我得到一个稍微不同的错误:AttributeError: 'UserObject' has no attribute 'has_module_perms'

完整回溯:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\manager.py", line 151, in get
    return self.get_queryset().get(*args, **kwargs)
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\query.py", line 298, in get
    clone = self.filter(*args, **kwargs)
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\query.py", line 590, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\query.py", line 608, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\sql\query.py", line 1198, in add_q
    clause = self._add_q(where_part, used_aliases)
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\sql\query.py", line 1232, in _add_q
    current_negated=current_negated)
  File "C:\Users\JJ\Coding\virtualenvs\TCR5venv\lib\site-packages\django\db\models\sql\query.py", line 1035, in build_filter
    arg, value = filter_expr
ValueError: too many values to unpack

客户用户模型:

class UserObject(AbstractBaseUser):

    email = models.EmailField(max_length=254, unique=True, db_index=True)

    USERNAME_FIELD = 'email'
    # REQUIRED_FIELDS = ['student_or_business',]

    # Tells us whether the UserObject is a business or student
    @property
    def type(self):
        if hasattr(self, 'Student'.lower()):
            return 'S'
        elif hasattr(self, 'BusinessHandler'.lower()):
            return 'B'
        else:
            raise TypeError, "UserObject has neither Student nor BusinessHandler connected."

    # Gets us the actual UserObject's accompanying object, whether Student or Business
    @property
    def get_profile_object(self):
        if self.type == 'S':
            return getattr(self, 'Student'.lower())
        elif self.type == 'B':
            return getattr(self, 'BusinessHandler'.lower()) # to take advantage of refactoring

    @property
    def is_student(self):
        return self.type == 'S'

    @property
    def is_business(self):
        return self.type == 'B'

    def relevant_item(self, input_tuple):
        '''
        Takes in a tuple of options for return in form (Student, Business[, other]).
        Returns the appropriate option depending
        '''
        if not 2 <= len(input_tuple) <= 3:
            raise TypeError, "relevant_item() requires a tuple of 2 or 3."
        else:
            if self.type == 'S':
                return input_tuple[0]
            elif self.type == 'B':
                return input_tuple[1]
            else:
                return input_tuple[2] if len(input_tuple) == 3 else None


    signup_date = models.DateTimeField(auto_now_add=True)

    # admin stuff
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    # Settings
    verified = models.BooleanField(default=False)
    accepted_TOS = models.DateField(default=datetime.datetime.today())
         # Date so can find who need to update when change TOS

    # Temporary hashes/strings
    verification_id = models.CharField(unique=True, default=lambda: random_string(20), max_length=20)
    reset_password_code = models.CharField(blank=True, default=lambda: random_string(20), max_length=20)

    def get_new_reset_password_code(self):
        self.reset_password_code = random_string(20)
        self.save()
        return self.reset_password_code

    def new_verification_id(self):
        self.verification_id = random_string(20)
        try:
            self.save()
        except IntegrityError:
            self.new_verification_id()

    objects = UserObjectManager()

自定义用户管理器:

class UserObjectManager(BaseUserManager):

    @staticmethod
    def create_accompanying_model(user, student_or_business):
        '''
        This creates the appropriate accompanying Student or BusinessHandler model when a
        new UserObject is created.
        '''

        if student_or_business == 'S':
            s = models.get_model('student', 'Student')
            new_item = s.objects.create(user_object=user, UserObject_creation=True)
            new_item.save()

        elif student_or_business == 'B':
            b = models.get_model('business', 'BusinessHandler')
            new_item = b.objects.create(user_object=user, UserObject_creation=True)
            new_item.save()

        else:
            msg = 'Must be Student or BusinessHandler.'
            raise ValueError(msg)

    def create_user(self, email, password, student_or_business):

        # normalize student_or_business
        if student_or_business.lower() in ('s', 'student'):
            student_or_business = 'S'
        elif student_or_business.lower() in ('b', 'business', 'BusinessHandler'.lower()):
            student_or_business = 'B'

        # Check if an email was provided
        if not email:
            msg = 'Users must have an email address.'
            raise ValueError(msg)

        # If a student, check if a '.edu' email address was provided
        if email and student_or_business == 'S':
            if not email.endswith('.edu'):
                msg = 'Students must sign up with a .edu email address.'
                raise ValueError(msg)

        user = self.model(
            email=UserObjectManager.normalize_email(email),

            # Removed the below because calculating that differently
            # student_or_business = student_or_business,

        )

        user.set_password(password)
        user.save(using=self._db)

        self.create_accompanying_model(user, student_or_business)

        return user

    def create_superuser(self, email, password, student_or_business):
        user = self.create_user(email, password, student_or_business)
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

谢谢!

最佳答案

事实证明,这里的问题实际上与抛出的错误无关。

我意识到我实际上是在打电话

UserObject.objects.get('user@email.com')

代替

UserObject.objects.get(email='user@email.com')

这就是抛出错误的原因。如果查看 Django 源代码,您会发现在为 QuerySet 构建过滤器时,Django 会解压字段名称和数据以供过滤器使用,但由于我没有提供字段名称到objects.get(...),解包时出现错误。

为此使用了 Werkzeug 实时浏览器调试器;我强烈推荐它。

关于python - Django:调用 user.objects.get() 时为 "Too many values to unpack",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820830/

有关python - Django:调用 user.objects.get() 时为 "Too many values to unpack"的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  5. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  6. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  7. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  8. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

随机推荐