Browse Source

Comply with PEP8

Rogdham 11 years ago
parent
commit
822b76acc2
7 changed files with 164 additions and 126 deletions
  1. 32 26
      coin/members/admin.py
  2. 7 4
      coin/members/membershipfee_filter.py
  3. 76 50
      coin/members/models.py
  4. 7 3
      coin/members/urls.py
  5. 7 5
      coin/members/views.py
  6. 26 27
      coin/settings.py
  7. 9 11
      coin/urls.py

+ 32 - 26
coin/members/admin.py

@@ -6,30 +6,28 @@ from coin.members.membershipfee_filter import DecadeBornListFilter
 import pprint
 
 
-
 # class LdapUserAdmin(admin.ModelAdmin):
 #    exclude = ['dn']
 #    list_display = ['uid','first_name', 'last_name']
 #    search_fields = ['first_name', 'last_name']
-    
     #TODO : Déplacer dans LdapUser model (pre_save ?)
     #def save_model(self, request, obj, form, change):
-        
-
 
 
 class CryptoKeyInline(admin.StackedInline):
     model = CryptoKey
     extra = 0
-    
+
+
 class MembershipFeeInline(admin.TabularInline):
     model = MembershipFee
     extra = 0
-    fields = ('start_date','end_date','amount')
+    fields = ('start_date', 'end_date', 'amount')
+
 
 class MemberAdminForm(forms.ModelForm):
     # password = forms.CharField(widget=forms.PasswordInput(), required=False)
-    
+
     def clean(self):
         cleaned_data = super(MemberAdminForm, self).clean()
         pprint.pprint(cleaned_data)
@@ -38,40 +36,48 @@ class MemberAdminForm(forms.ModelForm):
     class Meta:
         model = Member
 
+
 class MemberAdmin(admin.ModelAdmin):
-    list_display = ('id', 'status', 'first_name', 'last_name','email')
+    list_display = ('id', 'status', 'first_name', 'last_name', 'email')
     list_display_links = ('id', 'first_name', 'last_name')
-    list_filter = ('status',DecadeBornListFilter)
-    search_fields = ['first_name','last_name','email']
-    actions = ['set_as_member', 'set_as_non_member']
-    
-    fields =    ('status', 
-                'type', 
-                ('first_name', 'last_name', 'organization_name'), 
-                ('email', 'home_phone_number','mobile_phone_number'), 
-                'address', 
-                ('postal_code', 'city', 'country'), 
-                ('entry_date','resign_date'))
+    list_filter = ('status', DecadeBornListFilter)
+    search_fields = ('first_name', 'last_name', 'email')
+    actions = ('set_as_member', 'set_as_non_member')
+
+    fields = (
+        'status',
+        'type',
+        ('first_name', 'last_name', 'organization_name'),
+        ('email', 'home_phone_number', 'mobile_phone_number'),
+        'address',
+        ('postal_code', 'city', 'country'),
+        ('entry_date', 'resign_date'),
+    )
     radio_fields = {"type": admin.HORIZONTAL}
-    
+
     save_on_top = True
-    
+
     form = MemberAdminForm
     inlines = [CryptoKeyInline, MembershipFeeInline]
-    
+
     def set_as_member(self, request, queryset):
         rows_updated = queryset.update(status='adherent')
-        self.message_user(request, "%i membre(s) définis comme adhérent(s)." % rows_updated)
-    set_as_member.short_description = "Définir comme adhérent"
+        self.message_user(
+            request,
+            '%d membre(s) définis comme adhérent(s).' % rows_updated)
+    set_as_member.short_description = 'Définir comme adhérent'
 
     def set_as_non_member(self, request, queryset):
         rows_updated = queryset.update(status='non_adherent')
-        self.message_user(request, "%i membre(s) définis comme non adhérent(s)." % rows_updated)
+        self.message_user(
+            request,
+            '%d membre(s) définis comme non adhérent(s).' % rows_updated)
     set_as_non_member.short_description = "Définir comme non adhérent"
 
+
 class MembershipFeeAdmin(admin.ModelAdmin):
     list_display = ('member', 'end_date', 'amount')
-    
+
 
 admin.site.register(Member, MemberAdmin)
 admin.site.register(MembershipFee, MembershipFeeAdmin)

+ 7 - 4
coin/members/membershipfee_filter.py

@@ -2,6 +2,7 @@
 from django.contrib.admin import SimpleListFilter
 import datetime
 
+
 class DecadeBornListFilter(SimpleListFilter):
     # Human-readable title which will be displayed in the
     # right admin sidebar just above the filter options.
@@ -32,11 +33,13 @@ class DecadeBornListFilter(SimpleListFilter):
         # Compare the requested value (either '80s' or '90s')
         # to decide how to filter the queryset.
         if self.value() == 'ok':
-            return queryset.filter(membershipfee__start_date__lte=datetime.date.today,
-                                     membershipfee__end_date__gte=datetime.date.today)
+            return queryset.filter(
+                membershipfee__start_date__lte=datetime.date.today,
+                membershipfee__end_date__gte=datetime.date.today)
         if self.value() == 'retard':
-            return queryset.exclude(membershipfee__start_date__lte=datetime.date.today,
-                                     membershipfee__end_date__gte=datetime.date.today)
+            return queryset.exclude(
+                membershipfee__start_date__lte=datetime.date.today,
+                membershipfee__end_date__gte=datetime.date.today)
         #if self.value() == '90s':
             #return queryset.filter(birthday__gte=date(1990, 1, 1),
                                     #birthday__lte=date(1999, 12, 31))

+ 76 - 50
coin/members/models.py

@@ -1,6 +1,9 @@
 # -*- coding: utf-8 -*-
 import ldapdb.models
-import pprint, os #, base64, hashlib
+#import pprint
+import os
+#import base64
+#import hashlib
 from django.db import models
 from ldapdb.models.fields import CharField, IntegerField, ListField
 from django.db.models.signals import post_save, pre_save
@@ -11,92 +14,115 @@ from django.core import exceptions
 
 
 class LdapUser(ldapdb.models.Model):
-    base_dn = "ou=users,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR" #TODO déplacer dans settings.py
+    # TODO: déplacer ligne suivante dans settings.py
+    base_dn = "ou=users,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
     object_classes = ['inetOrgPerson', 'organizationalPerson', 'person', 'top']
 
-    uid = CharField(db_column='uid', unique=True,max_length=255)
-    nick_name = CharField(db_column='cn', unique=True, primary_key=True,max_length=255)
-    first_name = CharField(db_column='givenName',max_length=255)
-    last_name = CharField(db_column='sn',max_length=255)
-    display_name = CharField(db_column='displayName',max_length=255, blank=True)
-    password = CharField(db_column='userPassword',max_length=255)
+    uid = CharField(db_column='uid', unique=True, max_length=255)
+    nick_name = CharField(db_column='cn', unique=True, primary_key=True,
+                          max_length=255)
+    first_name = CharField(db_column='givenName', max_length=255)
+    last_name = CharField(db_column='sn', max_length=255)
+    display_name = CharField(db_column='displayName', max_length=255,
+                             blank=True)
+    password = CharField(db_column='userPassword', max_length=255)
 
     def __unicode__(self):
         return self.display_name
-    
+
     class Meta:
-        managed = False #Indique à South de ne pas gérer ce model
+        managed = False  # Indique à South de ne pas gérer ce model
+
+# Indique à South de ne pas gérer ce model
+add_ignored_fields(["^ldapdb\.models\.fields"])
 
-add_ignored_fields(["^ldapdb\.models\.fields"]) #Indique à South de ne pas gérer ce model
 
 class Member(models.Model):
 
-    MEMBER_TYPE_CHOICES =(('personne_physique','Personne physique'),('personne_morale','Personne morale'))
-    MEMBER_STATUS_CHOICES = (('adherent','Adhérent'),('non_adherent','Non adhérent'),('demande_adhesion','Demande d\'adhésion'))
-    
-    status = models.CharField(max_length=50, choices=MEMBER_STATUS_CHOICES, default='non_adherent');
-    type = models.CharField(max_length=20, choices=MEMBER_TYPE_CHOICES, default='personne_physique');
-    first_name = models.CharField(max_length=200);
-    last_name = models.CharField(max_length=200);
-    ldap_cn = models.CharField(max_length=200, blank=True);
-    organization_name = models.CharField(max_length=200, blank=True);
-    email = models.EmailField(max_length=254);
-    home_phone_number = models.CharField(max_length=25, blank=True);
-    mobile_phone_number = models.CharField(max_length=25, blank=True);
-    address = models.TextField();
-    postal_code = models.CharField(max_length=15);  
-    city = models.CharField(max_length=200);
-    country = models.CharField(max_length=200);
-    entry_date = models.DateField(null=False, blank=False, default=datetime.date.today);
-    resign_date = models.DateField(null=True, blank=True);
-        
+    MEMBER_TYPE_CHOICES = (
+        ('personne_physique', 'Personne physique'),
+        ('personne_morale', 'Personne morale'),
+    )
+    MEMBER_STATUS_CHOICES = (
+        ('adherent', 'Adhérent'),
+        ('non_adherent', 'Non adhérent'),
+        ('demande_adhesion', "Demande d'adhésion"),
+    )
+
+    status = models.CharField(max_length=50, choices=MEMBER_STATUS_CHOICES,
+                              default='non_adherent')
+    type = models.CharField(max_length=20, choices=MEMBER_TYPE_CHOICES,
+                            default='personne_physique')
+    first_name = models.CharField(max_length=200)
+    last_name = models.CharField(max_length=200)
+    ldap_cn = models.CharField(max_length=200, blank=True)
+    organization_name = models.CharField(max_length=200, blank=True)
+    email = models.EmailField(max_length=254)
+    home_phone_number = models.CharField(max_length=25, blank=True)
+    mobile_phone_number = models.CharField(max_length=25, blank=True)
+    address = models.TextField()
+    postal_code = models.CharField(max_length=15)
+    city = models.CharField(max_length=200)
+    country = models.CharField(max_length=200)
+    entry_date = models.DateField(null=False, blank=False,
+                                  default=datetime.date.today)
+    resign_date = models.DateField(null=True, blank=True)
+
     def __unicode__(self):
-        return self.first_name+' '+self.last_name;
+        return self.first_name + ' ' + self.last_name
 
 
 class CryptoKey(models.Model):
-    
-    KEY_TYPE_CHOICES=(('RSA','RSA'),('GPG','GPG'))
-    
-    type = models.CharField(max_length=3, choices=KEY_TYPE_CHOICES);
-    key = models.TextField();
-    member = models.ForeignKey('Member');
+
+    KEY_TYPE_CHOICES = (('RSA', 'RSA'), ('GPG', 'GPG'))
+
+    type = models.CharField(max_length=3, choices=KEY_TYPE_CHOICES)
+    key = models.TextField()
+    member = models.ForeignKey('Member')
 
     def __unicode__(self):
-        return self.member.__str__();
+        return self.member.__str__()
+
 
 class MembershipFee(models.Model):
-    member = models.ForeignKey('Member');
-    amount = models.IntegerField(null=False, default='20');
-    start_date = models.DateField(null=False, blank=False, default=datetime.date.today);
-    end_date = models.DateField(null=False, blank=False, default=datetime.date.today() + datetime.timedelta(365));
+    member = models.ForeignKey('Member')
+    amount = models.IntegerField(null=False, default='20')
+    start_date = models.DateField(null=False, blank=False,
+                                  default=datetime.date.today)
+    end_date = models.DateField(
+        null=False, blank=False,
+        default=datetime.date.today() + datetime.timedelta(365))
+
 
-#~ Lors de la sauvegarde d'un membre, cette fonction est exécutée pour mettre à jour les données dans le LDAP
 @receiver(post_save, sender=Member)
 def sync_ldap(sender, instance, created, **kwargs):
+    """
+    Update LDAP data when a member is saved
+    """
 
     if not created:
        # try:
             ldap_user = LdapUser.objects.get(pk=instance.ldap_cn)
        # except exceptions.ObjectDoesNotExist:
        #     created = True
-            
+
     if created:
         ldap_user = LdapUser()
         ldap_user.pk = instance.ldap_cn
         ldap_user.uid = instance.ldap_cn
         ldap_user.nick_name = instance.ldap_cn
-    
+
     ldap_user.last_name = instance.last_name
-    ldap_user.first_name  = instance.first_name
+    ldap_user.first_name = instance.first_name
     # ldap_user.password = instance.password
-    ldap_user.save();
+    ldap_user.save()
 
 
-#===============================================================================
+#==============================================================================
 # @receiver(pre_save, sender = LdapUser)
 # def ssha_password(sender, **kwargs):
 #     if not kwargs['instance'].password.startswith('{SSHA}'):
 #         salt = os.urandom(8).encode('hex')
-#         kwargs['instance'].password = '{SSHA}' + base64.b64encode(hashlib.sha1(obj.password + salt).digest() + salt)
-#===============================================================================
+#         kwargs['instance'].password = '{SSHA}' + base64.b64encode(
+    #         hashlib.sha1(obj.password + salt).digest() + salt)
+#==============================================================================

+ 7 - 3
coin/members/urls.py

@@ -3,9 +3,13 @@ from django.views.generic import DetailView
 from coin.members import views
 from coin.members.models import Member
 
-urlpatterns = patterns('',
+
+urlpatterns = patterns(
+    '',
     url(r'^$', views.index, name='index'),
-    url(r'^(?P<pk>\d+)/$', DetailView.as_view(
+    url(r'^(?P<pk>\d+)/$',
+        DetailView.as_view(
             model=Member,
-            template_name='members/detail.html'), name='detail')
+            template_name='members/detail.html'),
+        name='detail')
 )

+ 7 - 5
coin/members/views.py

@@ -1,17 +1,19 @@
-import pprint
-# from django.http import HttpResponse
+#import pprint
+from django.http import HttpResponse
 # from django.template import Context, loader
 from django.shortcuts import render, get_object_or_404
-from django.http import Http404
+#from django.http import Http404
 from coin.members.models import Member
 
 
 def index(request):
     return HttpResponse("Hello, world. You're at the members index.")
 
+
 def change_password(request, member_id):
     member = get_object_or_404(Member, pk=member_id)
     if request.POST['password']:
         member.password = ''
-    else :
-        return render(request, 'members/change_password.html', {'member':member})
+    else:
+        return render(request, 'members/change_password.html',
+                      {'member': member})

+ 26 - 27
coin/settings.py

@@ -1,7 +1,8 @@
 # -*- coding: utf-8 -*-
 import os
 import ldap
-from django_auth_ldap.config import LDAPSearch, GroupOfNamesType #, PosixGroupType
+from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
+#                                   , PosixGroupType
 from custom.coin_posix_group_type import CoinPosixGroupType
 
 # Django settings for coin project.
@@ -18,19 +19,18 @@ MANAGERS = ADMINS
 
 DATABASES = {
     'default': {
-        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
-        'NAME': 'illyse_coin',                      # Or path to database file if using sqlite3.
-        # The following settings are not used with sqlite3:
+        'ENGINE': 'django.db.backends.postgresql_psycopg2',
+        'NAME': 'illyse_coin',
         'USER': 'illyse_coin',
         'PASSWORD': '',
-        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
-        'PORT': '',                      # Set to empty string for default.
+        'HOST': '',  # Empty for localhost through domain sockets
+        'PORT': '',  # Empty for default
     },
     'ldap': {
-            'ENGINE': 'ldapdb.backends.ldap',
-            'NAME':    'ldap://localhost/',
-            'USER':    'cn=admin,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR',
-            'PASSWORD': 'admin'
+        'ENGINE': 'ldapdb.backends.ldap',
+        'NAME': 'ldap://localhost/',
+        'USER': 'cn=admin,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR',
+        'PASSWORD': 'admin'
     }
 }
 
@@ -94,7 +94,7 @@ STATICFILES_DIRS = (
 STATICFILES_FINDERS = (
     'django.contrib.staticfiles.finders.FileSystemFinder',
     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
-#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
+    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
 )
 
 # Make this unique, and don't share it with anybody.
@@ -104,7 +104,7 @@ SECRET_KEY = '!qy_)gao6q)57#mz1s-d$5^+dp1nt=lk1d19&9bb3co37vn)!3'
 TEMPLATE_LOADERS = (
     'django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader',
-#     'django.template.loaders.eggs.Loader',
+    #'django.template.loaders.eggs.Loader',
 )
 
 MIDDLEWARE_CLASSES = (
@@ -123,9 +123,7 @@ ROOT_URLCONF = 'coin.urls'
 WSGI_APPLICATION = 'coin.wsgi.application'
 
 TEMPLATE_DIRS = (
-    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
-    # Always use forward slashes, even on Windows.
-    # Don't forget to use absolute paths, not relative paths.
+    # Only absolute paths, always forward slashes
     os.path.join(PROJECT_PATH, 'templates/'),
 )
 
@@ -141,7 +139,7 @@ INSTALLED_APPS = (
     # Uncomment the next line to enable admin documentation:
     'django.contrib.admindocs',
     'south',
-    'ldapdb', #LDAP as database backend
+    'ldapdb',  # LDAP as database backend
     'coin.members'
 )
 
@@ -183,18 +181,24 @@ AUTH_LDAP_SERVER_URI = "ldap://localhost"
 
 AUTH_LDAP_BIND_DN = "cn=admin,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
 AUTH_LDAP_BIND_PASSWORD = "admin"
-AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR",
-    ldap.SCOPE_SUBTREE, "(cn=%(user)s)")
+AUTH_LDAP_USER_SEARCH = LDAPSearch(
+    "ou=users,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR",
+    ldap.SCOPE_SUBTREE,
+    "(cn=%(user)s)"
+)
 
 AUTH_LDAP_CACHE_GROUPS = False
 
-AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR",
-    ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)"
+AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
+    "ou=groups,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR",
+    ldap.SCOPE_SUBTREE,
+    "(objectClass=posixGroup)"
 )
 
 AUTH_LDAP_GROUP_TYPE = CoinPosixGroupType()
 
-#~ AUTH_LDAP_REQUIRE_GROUP = "cn=admin,ou=groups,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
+# AUTH_LDAP_REQUIRE_GROUP = "cn=admin,ou=groups,o=ILLYSE,"
+#                           "l=Villeurbanne,st=RHA,c=FR"
 
 AUTH_LDAP_USER_ATTR_MAP = {
     "first_name": "givenName",
@@ -208,13 +212,8 @@ AUTH_LDAP_USER_FLAGS_BY_GROUP = {
 }
 
 
-#~ Surcharge les paramètres en utilisant le fichier settings-local.py
+# Surcharge les paramètres en utilisant le fichier settings-local.py
 try:
     from settings_local import *
 except ImportError:
     pass
-
-
-
-
-

+ 9 - 11
coin/urls.py

@@ -1,21 +1,19 @@
 from django.conf.urls import patterns, include, url
-
 from django.contrib import admin
-admin.autodiscover()
 
-urlpatterns = patterns('',
-    # Examples:
-    # url(r'^$', 'coin.views.home', name='home'),
-    # url(r'^coin/', include('coin.foo.urls')),
+admin.autodiscover()
 
+urlpatterns = patterns(
+    '',
+    #url(r'^$', 'coin.views.home', name='home'),
 
-   # url(r'^members/password/$', 'django_ldapbackend.views.password_change'),
-    #url(r'^members/password/changed/$', 'django.contrib.auth.views.password_change_done'),
-    url(r'^members/login/$', 'django.contrib.auth.views.login', {'template_name': 'members/login.html'}),
+    #url(r'^members/password/$', 'django_ldapbackend.views.password_change'),
+    #url(r'^members/password/changed/$',
+    #    'django.contrib.auth.views.password_change_done'),
+    url(r'^members/login/$', 'django.contrib.auth.views.login',
+        {'template_name': 'members/login.html'}),
     url(r'^members/', include('coin.members.urls', namespace='members')),
-	
 
     url(r'^admin/', include(admin.site.urls)),
     url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
-
 )