[snowy: 21/26] Add ability to set username to initial preferences form



commit 8d7fe09a794bec75136cab0ad9fc0c121d5268f3
Author: Leon Handreke <leon handreke gmail com>
Date:   Mon May 24 20:19:01 2010 +0200

    Add ability to set username to initial preferences form

 accounts/forms.py                                  |   68 ++++++++-----------
 accounts/models.py                                 |   13 ++++-
 .../templates/accounts/initial_preferences.html    |   36 +++++++----
 accounts/views.py                                  |   29 ++++----
 lib/django_openid_auth/auth.py                     |    3 +
 lib/django_openid_auth/views.py                    |    2 +-
 site_media/css/accounts.css                        |   20 ++++++
 site_media/img/accounts/google-accounts-logo.png   |  Bin 7525 -> 7774 bytes
 site_media/img/accounts/openid.png                 |  Bin 0 -> 3203 bytes
 templates/base.html                                |    8 ++
 10 files changed, 111 insertions(+), 68 deletions(-)
---
diff --git a/accounts/forms.py b/accounts/forms.py
index 4e30635..27cf82e 100644
--- a/accounts/forms.py
+++ b/accounts/forms.py
@@ -15,23 +15,31 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 
+from django.contrib.auth.models import User
 from registration.forms import RegistrationFormUniqueEmail
 from django.utils.translation import ugettext_lazy as _
 from recaptcha_django import ReCaptchaField
 from django.conf import settings
 from django import forms
 
-class RegistrationFormUniqueUser(RegistrationFormUniqueEmail):
+def validate_username_blacklist(username):
     """
-    Subclass of ``RegistrationFormUniqueEmail`` which verifies usernames
-    against a blacklist.
+    Verifies that the username is not on the blacklist of reserved usernames
     """
-    captcha = ReCaptchaField(label=_(u'Verify words:'))
-
+    print "Validate"
     username_blacklist = ['about', 'accounts', 'admin', 'api', 'blog',
                           'contact', 'css', 'friends', 'images', 'index.html',
                           'news', 'notes', 'oauth', 'pony', 'register',
                           'registration', 'site_media', 'snowy', 'tomboy']
+    if username in username_blacklist:
+        raise forms.ValidationError(_(u'This username has been reserved.  Please choose another.'))
+
+class RegistrationFormUniqueUser(RegistrationFormUniqueEmail):
+    """
+    Subclass of ``RegistrationFormUniqueEmail`` which verifies usernames
+    against a blacklist and adds a captcha.
+    """
+    captcha = ReCaptchaField(label=_(u'Verify words:'))
 
     def __init__(self, *args, **kwargs):
         super(RegistrationFormUniqueUser, self).__init__(*args, **kwargs)
@@ -41,6 +49,8 @@ class RegistrationFormUniqueUser(RegistrationFormUniqueEmail):
         
         self.fields['username'].label = _(u'Username:')
         self.fields['username'].help_text = _(u'Maximum of 30 characters in length.')
+        self.fields['username'].validators = [validate_username_blacklist,
+                                              validate_username_available]
 
         self.fields['email'].label = _(u'Email address:')
 
@@ -50,12 +60,8 @@ class RegistrationFormUniqueUser(RegistrationFormUniqueEmail):
         self.fields['password2'].label = _(u'Re-enter password:')
 
     def clean_username(self):
-        """
-        Validate that the user doesn't exist in our blacklist.
-        """
         username = self.cleaned_data['username']
-        if username in self.username_blacklist:
-            raise forms.ValidationError(_(u'This username has been reserved.  Please choose another.'))
+        validate_username_blacklist(username)
         return username
 
     def clean_password1(self):
@@ -81,38 +87,22 @@ class DisplayNameChangeForm(forms.ModelForm):
         fields = ('display_name',)
 
 class EmailChangeForm(forms.ModelForm):
-    """
-    This code is adapted from
-    http://stackoverflow.com/questions/1075314/allow-changing-of-user-fields-like-email-with-django-profiles
-    """
+    class Meta:
+        model = User
+        fields = ('email', )
+
     def __init__(self, *args, **kwargs):
         super(EmailChangeForm, self).__init__(*args, **kwargs)
-        try:
-            self.fields['email'].initial = self.instance.user.email
-        except User.DoesNotExist:
-            pass
+        self.fields['email'].required = True
 
-    email = forms.EmailField(label="Email address")
+class UsernameChangeForm(forms.ModelForm):
+    class Meta:
+        model = User
+        fields = ('username', )
 
-    def save(self, *args, **kwargs):
-        """
-        Update the email address on the user object
-        """
-        u = self.instance.user
-        u.email = self.cleaned_data['email']
-        u.save()
-        return u.email
+    def clean_username(self):
+        username = self.cleaned_data['username']
+        validate_username_blacklist(username)
+        return username
 
-class InitialPreferencesForm(forms.ModelForm):
 
-    def __init__(self, *args, **kwargs):
-        super(InitialPreferencesForm, self).__init__(*args, **kwargs)
-        try:
-            self.fields['email'].initial = self.instance.user.email
-            self.fields['display_name'].initial = self.instance.display_name
-        except User.DoesNotExist:
-            pass
-
-    email = forms.EmailField(label="Email address")
-    display_name = forms.CharField(max_length=80, label="Display Name",
-                                   help_text="This name will be shown to other users when sharing notes")
diff --git a/accounts/models.py b/accounts/models.py
index 56aa642..eb5823a 100644
--- a/accounts/models.py
+++ b/accounts/models.py
@@ -33,12 +33,23 @@ class UserProfile(models.Model):
     language = models.CharField(max_length=5, choices=settings.LANGUAGES,
                                 verbose_name=_(u'Application Language'),
                                 null=True, blank=True)
-    display_name = models.CharField(_('display name'), max_length=80)
+    display_name = models.CharField(_('display name'), max_length=80,
+                                    blank=True,
+                                    help_text=_(u'Optional. Will be displayed to other users when sharing notes.'))
     openid_user = models.BooleanField(verbose_name=_(u'OpenID User'),)
 
     def __unicode__(self):
         return str(self.user)
 
+    def registration_complete(self):
+        """
+        Checks whether an OpenID user has given all of his user details
+        """
+        if self.openid_user:
+            if self.user.username[:10] == "openiduser" or self.user.email == "":
+                return False
+        return True
+
 def _create_profile(sender, instance, created, **kwargs):
     """
     Create a UserProfile object in response to a new User being created.
diff --git a/accounts/templates/accounts/initial_preferences.html b/accounts/templates/accounts/initial_preferences.html
index bbb5f3b..a771e7c 100644
--- a/accounts/templates/accounts/initial_preferences.html
+++ b/accounts/templates/accounts/initial_preferences.html
@@ -2,22 +2,34 @@
 
 {% load i18n %}
 
+{% block extra_head %}
+{{ block.super }}
+<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/accounts.css">
+{% endblock %}
+
 {% block content %}
 <h1>Tell {{ site.name }} about yourself!</h1>
 
 <form method="POST">
-    <table class="input-form">
-    {{ initial_preferences_form.as_table }}
-        <tfoot>
-            <tr>
-                <th></th>
-                <td>
-                    <input type="submit" value="{% trans "Save" %}"/>
-                </td>
-            </tr>
-        </tfoot>
-    </table>
-    <input type="hidden" name="initial_preferences_form" value="1" />
+    <p>
+      <label for="username" class="initial-preferences-label">{{ username_form.username.label }}:</label>
+      {{ username_form.username }}
+      <span class="initial-preferences-errors">{{ username_form.username.errors.0 }}</span>
+    </p>
+
+    <p>
+      <label for="email" class="initial-preferences-label">{{ email_form.email.label }}:</label>
+      {{ email_form.email }}
+      <span class="initial-preferences-errors">{{ email_form.email.errors.0 }}</span>
+    </p>
+
+    <p>
+      <label for="display_name" class="initial-preferences-label">{{ display_name_form.display_name.label }}:</label>
+      {{ display_name_form.display_name }}
+      <span class="initial-preferences-errors">{{ display_name_form.display_name.errors.0 }}</span>
+      <br /><span class="initial-preferences-help-text">{{ display_name_form.display_name.help_text }}<span>
+    </p>
+    <input type="submit" value="{% trans "Save" %}"/>
 </form>
 
 {% endblock %}
diff --git a/accounts/views.py b/accounts/views.py
index dadfaa2..f1a66d0 100644
--- a/accounts/views.py
+++ b/accounts/views.py
@@ -23,32 +23,31 @@ from django.template import RequestContext
 from django.conf import settings
 
 from snowy.accounts.forms import InternationalizationForm, EmailChangeForm, \
-    DisplayNameChangeForm, InitialPreferencesForm
+    DisplayNameChangeForm, UsernameChangeForm
 
 @login_required
 def initial_preferences(request, template_name='accounts/initial_preferences.html'):
     user = request.user
     profile = user.get_profile()
 
-    if 'initial_preferences_form' in request.POST:
-        email_form = EmailChangeForm(request.POST, instance=profile)
-        if email_form.is_valid():
-            print 'Email form is valid!'
-            email_form.save()
+    username_form = UsernameChangeForm(request.POST or None, instance=user)
+    email_form = EmailChangeForm(request.POST or None, instance=user)
+    display_name_form = DisplayNameChangeForm(request.POST or None, instance=profile)
 
-        display_name_form = DisplayNameChangeForm(request.POST, instance=profile)
-        if display_name_form.is_valid():
-            print 'Display Name form is valid!'
-            display_name_form.save()
-
-        if email_form.is_valid() and display_name_form.is_valid():
-            return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
+    forms = [username_form, email_form, display_name_form]
+    for form in forms:
+        if form.is_valid():
+            form.save()
 
-    initial_preferences_form = InitialPreferencesForm(instance=profile)
+    # redirect if all forms are valid
+    if all(form.is_valid() for form in forms):
+        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
 
     return render_to_response(template_name,
                               {'user': user,
-                               'initial_preferences_form' : initial_preferences_form},
+                               'username_form' : username_form,
+                               'email_form' : email_form,
+                               'display_name_form' : display_name_form},
                               context_instance=RequestContext(request))
 
 @login_required
diff --git a/lib/django_openid_auth/auth.py b/lib/django_openid_auth/auth.py
index bccd729..f277d8e 100644
--- a/lib/django_openid_auth/auth.py
+++ b/lib/django_openid_auth/auth.py
@@ -120,7 +120,10 @@ class OpenIDBackend:
             i += 1
 
         user = User.objects.create_user(username, email, password=None)
+        print user
         user.get_profile().openid_user = True
+        user.get_profile().save()
+        print str(user.get_profile().openid_user)
 
         if sreg_response:
             self.update_user_details_from_sreg(user, sreg_response)
diff --git a/lib/django_openid_auth/views.py b/lib/django_openid_auth/views.py
index d3c8bfe..1144adc 100644
--- a/lib/django_openid_auth/views.py
+++ b/lib/django_openid_auth/views.py
@@ -208,7 +208,7 @@ def login_complete(request, redirect_field_name=REDIRECT_FIELD_NAME):
             if user.is_active:
                 auth_login(request, user)
                 # Check if the user has filled in relevant credentials
-                if (user.get_profile().display_name and user.email):
+                if (user.get_profile().registration_complete()):
                     return HttpResponseRedirect(sanitise_redirect_url(redirect_to))
                 else:
                     return HttpResponseRedirect(reverse('initial_preferences'))
diff --git a/site_media/css/accounts.css b/site_media/css/accounts.css
index 4e85dad..dc8786f 100644
--- a/site_media/css/accounts.css
+++ b/site_media/css/accounts.css
@@ -18,4 +18,24 @@
     display: block;
     float: left;
     margin-left: 10px;
+}
+
+.initial-preferences-label {
+    width: 10em;
+    font-weight: bold;
+    text-align: right;
+    display: inline-block;
+    margin-right: 0.5em;
+}
+
+.initial-preferences-errors {
+    color: red;
+    margin-left: 2em;
+}
+
+.initial-preferences-help-text {
+    /* set the help text off from the input field above it */
+    line-height: 2;
+    /* make the help text align with the input field above it */
+    margin-left: 11em;
 }
\ No newline at end of file
diff --git a/site_media/img/accounts/google-accounts-logo.png b/site_media/img/accounts/google-accounts-logo.png
index 601b457..f8057ff 100644
Binary files a/site_media/img/accounts/google-accounts-logo.png and b/site_media/img/accounts/google-accounts-logo.png differ
diff --git a/site_media/img/accounts/openid.png b/site_media/img/accounts/openid.png
new file mode 100644
index 0000000..791b108
Binary files /dev/null and b/site_media/img/accounts/openid.png differ
diff --git a/templates/base.html b/templates/base.html
index 455dd7d..56c0b52 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -31,11 +31,15 @@
                 <td id="header-auth">
 {% if user.is_authenticated %}
                     <h3>
+                      {% if user.get_profile.registration_complete %}
                       {% if user.get_profile.display_name %}
                       {{ user.get_profile.display_name }}
                       {% else %}
                       {{ user }}
                       {% endif %}
+                      {% else %}
+                      {% trans "OpenID User" %}
+                      {% endif %}
                     </h3>
                     <p><a href="{% url preferences %}">{% trans "preferences" %}</a> / <a href="{% url django.contrib.auth.views.logout %}">{% trans "log out" %}</a></p>
 {% else %}
@@ -45,7 +49,11 @@
                 </td>
                 <td id="header-avatar">
 {% if user.is_authenticated %}
+{% if user.get_profile.registration_complete %}
                     <a href="{% url notes.views.note_index user.username %}">{% gravatar_img_for_user user 64 %}</a>
+{% else %}
+                    <img src="{{MEDIA_URL}}/img/accounts/openid.png" height="64" width="64" alt="OpenID icon">
+{% endif %}
 {% endif %}
                 </td>
             </tr>



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]