向django注册添加邀请代码

向django注册添加邀请代码,django,registration,Django,Registration,正在尝试向django注册添加邀请代码。我知道有一个名为“邀请”的注册软件包,可以处理它,但似乎应该这样做。这是注册表格的代码。py: class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested username is not already in use, and requires the passwo

正在尝试向django注册添加邀请代码。我知道有一个名为“邀请”的注册软件包,可以处理它,但似乎应该这样做。这是注册表格的代码。py:

class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.

    Validates that the requested username is not already in use, and
    requires the password to be entered twice to catch typos.

    Subclasses should feel free to add any additional validation they
    need, but should avoid defining a ``save()`` method -- the actual
    saving of collected user data is delegated to the active
    registration backend.

    """
    required_css_class = 'required'

    username = forms.RegexField(regex=r'^[\w.@+-]+$',
                            max_length=30,
                            label=_("Username"),
                            error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    email = forms.EmailField(label=_("E-mail"))
    password1 = forms.CharField(widget=forms.PasswordInput,
                            label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput,
                            label=_("Password (again)"))
i    code = forms.CharField(widget=forms.PasswordInput,
                            label=_("Invitation Code"))

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
    in use.

        """
        existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
        if existing.exists():
            raise forms.ValidationError(_("A user with that username already exists."))
        else:
            return self.cleaned_data['username']

    def clean(self):
    """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.

        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return self.cleaned_data

    def inviteCode(self):
        """
    Validate invitation code, ==happytimes
    """
    if 'icode' != 'happytimes':
        raise forms.ValidationError(_("You need a valid invite code to register, try again or contact us!"))
    else:
        return self.cleaned_data['icode']
我得到的integrityerror列用户id不唯一。我做错了什么?这个问题似乎与SQLITE3DB有关,但我不能确定

根据通知中的请求,以下是回溯:

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
  48.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\registration\views.py" in dispatch
  79.         return super(RegistrationView, self).dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
  69.         return handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\registration\views.py" in post
  35.             return self.form_valid(request, form)
File "C:\Python27\lib\site-packages\registration\views.py" in form_valid
  82.         new_user = self.register(request, **form.cleaned_data)
File "C:\Python27\lib\site-packages\registration\backends\default\views.py" in register
  80.                                                                     password, site)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
  224.                 return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\registration\models.py" in create_inactive_user
  88.         registration_profile = self.create_profile(new_user)
File "C:\Python27\lib\site-packages\registration\models.py" in create_profile
  112.                            activation_key=activation_key)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in create
  137.         return self.get_query_set().create(**kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in create
  377.         obj.save(force_insert=True, using=self.db)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
  463.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
  551.                 result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in _insert
  203.         return insert_query(self.model, objs, fields, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in insert_query
  1593.     return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  912.             cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  40.             return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  344.             return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /accounts/register/
Exception Value: column user_id is not unique
以下是我认为与models.py相关的部分:

def create_inactive_user(self, username, email, password,
                             site, send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.

        By default, an activation email will be sent to the new
        user. To disable this, pass ``send_email=False``.

        """
        new_user = User.objects.create_user(username, email, password,)
        new_user.is_active = False
        new_user.save()

        registration_profile = self.create_profile(new_user)

        if send_email:
            registration_profile.send_activation_email(site)

        return new_user
    create_inactive_user = transaction.commit_on_success(create_inactive_user)

    def create_profile(self, user):
        """
        Create a ``RegistrationProfile`` for a given
        ``User``, and return the ``RegistrationProfile``.

        The activation key for the ``RegistrationProfile`` will be a
        SHA1 hash, generated from a combination of the ``User``'s
        username and a random salt.

        """
        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
        username = user.username
        if isinstance(username, unicode):
            username = username.encode('utf-8')
        activation_key = hashlib.sha1(salt+username).hexdigest()
        return self.create(user=user,
                           activation_key=activation_key)
检查icode行的拼写。你在上面贴了个空格

此外,这种逻辑是不正确的:

如果'icode'!='“快乐时光”:

您正在比较两个字符串

而且,我认为您希望使inviteCode干净\u icode,并在那里运行逻辑:

def clean_icode(self):
    """
    Validate invitation code, ==happytimes
    """
    if self.cleaned_data['icode'] != 'happytimes':
        raise forms.ValidationError(_("You need a valid invite code to register, try again or contact us!"))
   else:
        return self.cleaned_data['icode']

回溯表明具有所述用户标识的注册配置文件已经存在。这很可能是因为用户表已被删除,重置了id列的自动增量状态,但注册配置文件的表尚未清除。新生成的用户id与旧的、已删除的用户id冲突,这会导致IntegrityError,因为注册配置文件表中的用户id字段不再是唯一的


此问题通常仅在SQLite3中遇到,因为默认情况下不会检查外键约束的完整性错误。这允许您删除用户表或其条目,而无需删除注册配置文件或将外键设置为NULL

请发布完整的回溯,如果您使用的是自定义用户模型,请提供模型的代码。添加了回溯。这不是一个自定义的用户模型,我只是希望invite代码返回true,然后触发其余代码,即创建新的用户实例,然后发送验证电子邮件。似乎该特定用户id的注册配置文件已经存在。您是否在不清空注册配置文件表的情况下删除了用户表并重新创建了它?@knbk您是对的。不再获得完整性错误。验证邀请代码的函数没有运行,但我想我可以找到答案。谢谢那么您也可以认为这是SQLite问题:SQLite3默认情况下不检查外键约束的完整性。这允许您在不正确处理注册配置文件表的情况下首先删除用户表。这很有意义。然而,仍然没有结果。上面添加了回溯。需要查看models.py。您可能需要将用户id添加到表单中