添加邀请代码到django注册

时间:2014-06-23 21:58:40

标签: django registration

尝试向django注册添加邀请代码。我知道有一个名为邀请的注册包,可以处理它,但它似乎应该是注册form.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列user_id不是唯一的。我究竟做错了什么?这个问题似乎与sqlite3 db有关,但我无法确定。

根据提交中的请求,这里是追溯:

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)

2 个答案:

答案 0 :(得分:0)

检查icode行的拼写。你用空格粘贴它。

此外,这种逻辑不正确:

if 'icode' != 'happytimes':

您正在比较2个字符串。

并且,我认为你想要inviteCode clean_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']

答案 1 :(得分:0)

回溯表示已存在具有所述user_id的注册配置文件。这很可能是因为用户表已被删除(重置auto_increment列的id状态),但注册配置文件的表尚未清除。由于注册个人资料表中的user_id字段不再具有唯一性,因此新生成的user_id与旧版IntegrityError发生冲突,导致user_id

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