title: Adding invitation code to django registration
body: <p>Trying to add an invite code to django registration. I know there is a package for registration called invitation that would take care of it but it seems like it should Here is the code for registration forms.py:</p>
  
  <pre><code>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']
  </code></pre>
  
  <p>I'm getting an integrityerror column user_id not unique. What am I doing wrong? The issue seems to have something to do with the sqlite3 db, but I can't be sure. </p>
  
  <p>Per the request in the commment, here is the traceback:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Here is, what I believe is the relevant section of models.py:</p>
  
  <pre><code>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)
  </code></pre>