From 09556d0f38c99a63a19492e1429e514c3bd40c9b Mon Sep 17 00:00:00 2001 From: Yoan Le Clanche Date: Thu, 16 Dec 2021 17:26:39 +0100 Subject: [PATCH] Convert to python 3 --- teleforma/admin.py | 17 +++++++------- teleforma/fields.py | 16 ++++++-------- .../teleforma-cleanup-testimonials.py | 4 ++-- .../commands/teleforma-copy-seminars.py | 6 ++--- .../commands/teleforma-export-avis.py | 4 ++-- .../commands/teleforma-export-professors.py | 2 +- .../commands/teleforma-export-users.py | 20 ++++++++--------- .../teleforma-extract-kdenlive-markers.py | 2 +- .../commands/teleforma-import-courses-xls.py | 2 +- .../commands/teleforma-import-professors.py | 2 +- .../teleforma-import-seminar-media-update.py | 4 ++-- .../teleforma-import-seminar-media.py | 4 ++-- .../teleforma-import-seminars-preview.py | 2 +- .../teleforma-import-users-pb-debug.py | 2 +- .../commands/teleforma-import-users-pb.py | 2 +- .../commands/teleforma-import-users.py | 2 +- .../teleforma-remove-seminars-from-csv.py | 16 +++++++------- ...eforma-reset-all-passwords-with-mail-ae.py | 2 +- ...teleforma-reset-all-passwords-with-mail.py | 2 +- .../commands/teleforma-revisions-from-bbb.py | 18 +++++++-------- ...__add_answer__add_seminar__add_field_do.py | 4 ++-- ...dd_testimonialtemplate__add_testimonial.py | 6 ++--- ...50_auto__add_field_testimonial_template.py | 2 +- ...ield_testimonialtemplate_template_doc__.py | 4 ++-- teleforma/models/__init__.py | 8 +++---- teleforma/models/core.py | 4 ++-- teleforma/models/pro.py | 8 +++---- teleforma/templatetags/teleforma_tags.py | 20 ++++++++--------- teleforma/utils/unicode.py | 4 ++-- teleforma/views/__init__.py | 10 ++++----- teleforma/views/core.py | 22 +++++++++---------- teleforma/views/crfpa.py | 6 ++--- teleforma/views/home.py | 2 +- teleforma/views/pro.py | 22 +++++++++---------- 34 files changed, 123 insertions(+), 128 deletions(-) diff --git a/teleforma/admin.py b/teleforma/admin.py index f1f9ea3e..6bceda99 100644 --- a/teleforma/admin.py +++ b/teleforma/admin.py @@ -5,8 +5,7 @@ from teleforma.templatetags.teleforma_tags import fancy_duration_shop_like, fanc from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin -from longerusername.forms import UserCreationForm, UserChangeForm -from django.contrib.contenttypes.generic import GenericInlineModelAdmin +# from longerusername.forms import UserCreationForm, UserChangeForm from django.http import HttpResponse import time from datetime import date @@ -44,8 +43,8 @@ class ProfessorAdmin(admin.ModelAdmin): class UserProfileAdmin(UserAdmin): inlines = [ProfessorProfileInline, AuditorProfileInline] - add_form = UserCreationForm - form = UserChangeForm + # add_form = UserCreationForm + # form = UserChangeForm list_filter = ['is_staff', 'is_superuser', 'is_active', 'date_joined'] actions = ['export_user_profiles'] @@ -198,11 +197,11 @@ class ConferenceAdmin(admin.ModelAdmin): title = conference.pretty_title if conference.webclass: - title = u"Webconférence - " + title + title = "Webconférence - " + title if conference.duration: - title += u" - Durée : %s" % (fancy_duration_shop_like(conference.duration)) + title += " - Durée : %s" % (fancy_duration_shop_like(conference.duration)) if conference.webclass: - title += u" (%s live + %s de validation des acquis)" % (fancy_seconds(conference.webclass_duration), fancy_seconds(conference.webclass_hours_complementary.as_seconds())) + title += " (%s live + %s de validation des acquis)" % (fancy_seconds(conference.webclass_duration), fancy_seconds(conference.webclass_hours_complementary.as_seconds())) row = (conference.id, title, conference.price, conference.product_code) writer.writerow(row) return response @@ -342,10 +341,10 @@ class SeminarRevisionAdmin(admin.ModelAdmin): writer = UnicodeWriter(response, delimiter=";") writer.writerow(["seminaire", "email", "duree total", "date debut", "date fin", "duree"]) - for seminar in data.keys(): + for seminar in list(data.keys()): title = data[seminar]['title'] users = data[seminar]['users'] - for user in users.keys(): + for user in list(users.keys()): l = [title, user] revs = users[user] duration = datetime.timedelta() diff --git a/teleforma/fields.py b/teleforma/fields.py index ba36db5d..06bc6921 100644 --- a/teleforma/fields.py +++ b/teleforma/fields.py @@ -50,7 +50,7 @@ class Duration(object): def __add__(self, other): return self.__decorate(self._delta.__add__, other) - def __nonzero__(self): + def __bool__(self): return self._delta.__nonzero__() def __str__(self): @@ -79,7 +79,7 @@ class Duration(object): return Duration(hours=hours, minutes=minutes, seconds=seconds) except TypeError: - print groups + print(groups) raise else: raise ValueError("Malformed duration string: " + str) @@ -97,14 +97,14 @@ def normalize_field(args, default_value=None): The default value can also be overriden with the default=value argument. """ required = False - if args.has_key('required'): + if 'required' in args: required = args['required'] args.pop('required') args['blank'] = not required if not required: - if not args.has_key('default'): + if 'default' not in args: if args.get('null'): args['default'] = None elif default_value is not None: @@ -114,7 +114,7 @@ def normalize_field(args, default_value=None): # The following is based on Django TimeField -class DurationField(models.Field): +class DurationField(models.Field, metaclass=models.SubfieldBase): """Duration Django model field. Essentially the same as a TimeField, but with values over 24h allowed. @@ -123,8 +123,6 @@ class DurationField(models.Field): description = _("Duration") - __metaclass__ = models.SubfieldBase - default_error_messages = { 'invalid': _('Enter a valid duration in HH:MM[:ss] format.'), } @@ -138,7 +136,7 @@ class DurationField(models.Field): def to_python(self, value): if value is None: return None - if isinstance(value, int) or isinstance(value, long): + if isinstance(value, int): return Duration(seconds=value) if isinstance(value, datetime.time): return Duration(hours=value.hour, minutes=value.minute, seconds=value.second) @@ -169,7 +167,7 @@ class DurationField(models.Field): if val is None: data = '' else: - data = unicode(val) + data = str(val) return data def formfield(self, **kwargs): diff --git a/teleforma/management/commands/teleforma-cleanup-testimonials.py b/teleforma/management/commands/teleforma-cleanup-testimonials.py index af0323cf..9af710a7 100644 --- a/teleforma/management/commands/teleforma-cleanup-testimonials.py +++ b/teleforma/management/commands/teleforma-cleanup-testimonials.py @@ -36,7 +36,7 @@ class Command(BaseCommand): for testimonial2 in testimonials: if testimonial2.date_added < testimonial1.date_added: testimonial2.delete() - print ('kept', testimonial1.title, testimonial1.date_added) - print ('deleted', testimonial2.title, testimonial2.date_added) + print(('kept', testimonial1.title, testimonial1.date_added)) + print(('deleted', testimonial2.title, testimonial2.date_added)) diff --git a/teleforma/management/commands/teleforma-copy-seminars.py b/teleforma/management/commands/teleforma-copy-seminars.py index e4af466b..a9ef9477 100644 --- a/teleforma/management/commands/teleforma-copy-seminars.py +++ b/teleforma/management/commands/teleforma-copy-seminars.py @@ -59,12 +59,12 @@ class Command(BaseCommand): clone.status = 1 clone.quiz = seminar.quiz clone.save() - log = 'new seminar:' + unicode(clone) + log = 'new seminar:' + str(clone) logger.logger.info(log) - print log + print(log) log = 'http://' + self.site.domain + reverse('teleforma-seminar-detail', kwargs={'pk': clone.id}) logger.logger.info(log) - print log + print(log) for field in seminar._meta.many_to_many: diff --git a/teleforma/management/commands/teleforma-export-avis.py b/teleforma/management/commands/teleforma-export-avis.py index cff0e699..d2d30e4c 100644 --- a/teleforma/management/commands/teleforma-export-avis.py +++ b/teleforma/management/commands/teleforma-export-avis.py @@ -9,7 +9,7 @@ from pbcart.models import Cart import logging from datetime import datetime, timedelta, date import csv -import StringIO +import io from ftplib import FTP from teleforma.context_processors import seminar_validated @@ -41,7 +41,7 @@ class Command(BaseCommand): print(dry_run) logging.info('Generate csv file...') - output = StringIO.StringIO() + output = io.StringIO() writer = csv.writer(output, delimiter=';') writer.writerow([ diff --git a/teleforma/management/commands/teleforma-export-professors.py b/teleforma/management/commands/teleforma-export-professors.py index 4b7d620b..bfbf8b43 100644 --- a/teleforma/management/commands/teleforma-export-professors.py +++ b/teleforma/management/commands/teleforma-export-professors.py @@ -24,7 +24,7 @@ class Command(BaseCommand): 'email': user.email, 'courses': courses, }) - print 'exported: ' + user.first_name + ' ' + user.last_name + ' ' + user.username + print('exported: ' + user.first_name + ' ' + user.last_name + ' ' + user.username) return json.dumps(list) diff --git a/teleforma/management/commands/teleforma-export-users.py b/teleforma/management/commands/teleforma-export-users.py index 7ec6f204..6b06c965 100644 --- a/teleforma/management/commands/teleforma-export-users.py +++ b/teleforma/management/commands/teleforma-export-users.py @@ -23,17 +23,17 @@ class Command(BaseCommand): row.write(0, user.last_name) row.write(1, user.first_name) row.write(9, user.email) - row.write(2, unicode(student.iej)) + row.write(2, str(student.iej)) code = student.training.code if student.platform_only: code = 'I - ' + code - row.write(3, unicode(code)) - row.write(4, unicode(student.procedure.code)) - row.write(5, unicode(student.written_speciality.code)) - row.write(6, unicode(student.oral_speciality.code)) - row.write(7, unicode(student.oral_1.code)) - row.write(8, unicode(student.oral_2.code)) - row.write(15, unicode(student.period)) + row.write(3, str(code)) + row.write(4, str(student.procedure.code)) + row.write(5, str(student.written_speciality.code)) + row.write(6, str(student.oral_speciality.code)) + row.write(7, str(student.oral_1.code)) + row.write(8, str(student.oral_2.code)) + row.write(15, str(student.period)) profile = Profile.objects.filter(user=user) if profile: @@ -44,7 +44,7 @@ class Command(BaseCommand): row.write(13, profile.telephone) row.write(14, profile.date_added.strftime("%d/%m/%Y")) - print 'exported: ' + user.first_name + ' ' + user.last_name + ' ' + user.username + print('exported: ' + user.first_name + ' ' + user.last_name + ' ' + user.username) def export(self): self.book = Workbook() @@ -57,7 +57,7 @@ class Command(BaseCommand): row.write(3, 'FORMATION') row.write(4, 'PROC') row.write(5, 'Ecrit Spe') - row.write(6, unicode('Oral Spe')) + row.write(6, str('Oral Spe')) row.write(7, 'ORAL 1') row.write(8, 'ORAL 2') row.write(9, 'MAIL') diff --git a/teleforma/management/commands/teleforma-extract-kdenlive-markers.py b/teleforma/management/commands/teleforma-extract-kdenlive-markers.py index c2a931df..8988fb10 100644 --- a/teleforma/management/commands/teleforma-extract-kdenlive-markers.py +++ b/teleforma/management/commands/teleforma-extract-kdenlive-markers.py @@ -12,5 +12,5 @@ class Command(BaseCommand): media_file = args[0] session = KDEnLiveSession(media_file) for mark in session.markers(): - print mark['session_timecode'], mark['time'], mark['comment'] + print(mark['session_timecode'], mark['time'], mark['comment']) diff --git a/teleforma/management/commands/teleforma-import-courses-xls.py b/teleforma/management/commands/teleforma-import-courses-xls.py index 67b23b2a..a6e79643 100644 --- a/teleforma/management/commands/teleforma-import-courses-xls.py +++ b/teleforma/management/commands/teleforma-import-courses-xls.py @@ -39,5 +39,5 @@ class Command(BaseCommand): ) if created: - print 'imported: ' + course.title + print('imported: ' + course.title) diff --git a/teleforma/management/commands/teleforma-import-professors.py b/teleforma/management/commands/teleforma-import-professors.py index c2e6a33b..b4060a51 100644 --- a/teleforma/management/commands/teleforma-import-professors.py +++ b/teleforma/management/commands/teleforma-import-professors.py @@ -30,7 +30,7 @@ class Command(BaseCommand): course = Course.objects.filter(code=code) if course: p.courses.add(course[0]) - print 'imported: ' + user.first_name + ' ' + user.last_name + ' ' + user.username + print('imported: ' + user.first_name + ' ' + user.last_name + ' ' + user.username) def handle(self, *args, **options): file = args[0] diff --git a/teleforma/management/commands/teleforma-import-seminar-media-update.py b/teleforma/management/commands/teleforma-import-seminar-media-update.py index 62087e6d..029d7f16 100644 --- a/teleforma/management/commands/teleforma-import-seminar-media-update.py +++ b/teleforma/management/commands/teleforma-import-seminar-media-update.py @@ -136,7 +136,7 @@ class Command(BaseCommand): and not 'preview' in filename and not 'Preview' in filename and filename[0] != '.' \ and statinfo.st_size > self.size_limit: - print path + print(path) # seminar_rank <= 9 seminar_rank = int(root_list[-1][0]) @@ -265,4 +265,4 @@ class Command(BaseCommand): seminar.save() for s in seminars: - print 'http://' + self.site.domain + reverse('teleforma-seminar-detail', kwargs={'pk': s.id}) + print('http://' + self.site.domain + reverse('teleforma-seminar-detail', kwargs={'pk': s.id})) diff --git a/teleforma/management/commands/teleforma-import-seminar-media.py b/teleforma/management/commands/teleforma-import-seminar-media.py index a6d75cab..1c229cc6 100644 --- a/teleforma/management/commands/teleforma-import-seminar-media.py +++ b/teleforma/management/commands/teleforma-import-seminar-media.py @@ -127,7 +127,7 @@ class Command(BaseCommand): name = os.path.splitext(filename)[0] ext = os.path.splitext(filename)[1][1:] root_list = root.split(os.sep) - print root + os.sep + filename + print(root + os.sep + filename) if ext in self.original_format and not 'preview' in root_list \ and not 'preview' in filename and not 'Preview' in filename and filename[0] != '.': @@ -261,4 +261,4 @@ class Command(BaseCommand): seminar.save() for s in seminars: - print 'http://' + self.site.domain + reverse('teleforma-seminar-detail', kwargs={'pk': s.id}) + print('http://' + self.site.domain + reverse('teleforma-seminar-detail', kwargs={'pk': s.id})) diff --git a/teleforma/management/commands/teleforma-import-seminars-preview.py b/teleforma/management/commands/teleforma-import-seminars-preview.py index 9781d311..c9180353 100644 --- a/teleforma/management/commands/teleforma-import-seminars-preview.py +++ b/teleforma/management/commands/teleforma-import-seminars-preview.py @@ -199,4 +199,4 @@ class Command(BaseCommand): seminar.media_preview = media seminar.save() - print 'Done!' \ No newline at end of file + print('Done!') \ No newline at end of file diff --git a/teleforma/management/commands/teleforma-import-users-pb-debug.py b/teleforma/management/commands/teleforma-import-users-pb-debug.py index 10c5a3c7..352af544 100644 --- a/teleforma/management/commands/teleforma-import-users-pb-debug.py +++ b/teleforma/management/commands/teleforma-import-users-pb-debug.py @@ -84,7 +84,7 @@ class Command(BaseCommand): profile.telephone = row[13].value profile.save() student.save() - print 'imported: ' + first_name + ' ' + last_name + ' ' + username + print('imported: ' + first_name + ' ' + last_name + ' ' + username) def handle(self, *args, **options): file = args[0] diff --git a/teleforma/management/commands/teleforma-import-users-pb.py b/teleforma/management/commands/teleforma-import-users-pb.py index 44802192..2eb19b88 100644 --- a/teleforma/management/commands/teleforma-import-users-pb.py +++ b/teleforma/management/commands/teleforma-import-users-pb.py @@ -88,7 +88,7 @@ class Command(BaseCommand): profile.telephone = row[13].value profile.save() student.save() - print 'imported: ' + first_name + ' ' + last_name + ' ' + username + print('imported: ' + first_name + ' ' + last_name + ' ' + username) def handle(self, *args, **options): file = args[0] diff --git a/teleforma/management/commands/teleforma-import-users.py b/teleforma/management/commands/teleforma-import-users.py index 54aade85..90beec0b 100644 --- a/teleforma/management/commands/teleforma-import-users.py +++ b/teleforma/management/commands/teleforma-import-users.py @@ -63,7 +63,7 @@ class Command(BaseCommand): profile.telephone = row[13].value profile.save() student.save() - print 'imported: ' + first_name + ' ' + last_name + ' ' + username + print('imported: ' + first_name + ' ' + last_name + ' ' + username) def handle(self, *args, **options): file = args[0] diff --git a/teleforma/management/commands/teleforma-remove-seminars-from-csv.py b/teleforma/management/commands/teleforma-remove-seminars-from-csv.py index 4f4454a1..b103ca64 100644 --- a/teleforma/management/commands/teleforma-remove-seminars-from-csv.py +++ b/teleforma/management/commands/teleforma-remove-seminars-from-csv.py @@ -40,7 +40,7 @@ class Command(BaseCommand): elif key in ('commentaires', 'commentaire') and seminar: if val == 'non': if not '(' in seminar or not seminar.endswith(')'): - print("WARNING: malformed seminar %s" % seminar) + print(("WARNING: malformed seminar %s" % seminar)) continue title, sid = seminar.rsplit('(', 1) sid = sid[:-1] @@ -48,10 +48,10 @@ class Command(BaseCommand): seminar = list(Seminar.objects.filter(pk = sid)[:1]) seminar = seminar and seminar[0] if not seminar: - print('WARNING: Seminar %s not found' % sid) + print(('WARNING: Seminar %s not found' % sid)) wanted_title = str(seminar).strip() if title != wanted_title: - print("WARNING: Seminar %s: mismatched title %r %r" % (sid, title, wanted_title)) + print(("WARNING: Seminar %s: mismatched title %r %r" % (sid, title, wanted_title))) todel.append(seminar) else: seminar = None @@ -62,22 +62,22 @@ class Command(BaseCommand): user = list(User.objects.filter(email = email)[:1]) user = user and user[0] if not user: - print("WARNING: user %s not found" % email) + print(("WARNING: user %s not found" % email)) return auditor = list(user.auditor.all()[:1]) auditor = auditor and auditor[0] if not auditor: - print("WARNING: auditor for user %s not found" % email) + print(("WARNING: auditor for user %s not found" % email)) return existing = auditor.seminars.all().values('id') existing = set([ sem['id'] for sem in existing ]) - print("===> ", email) + print(("===> ", email)) for seminar in todel: if seminar.pk in existing: - print seminar + print(seminar) auditor.seminars.remove(seminar) else: - print("WARNING: seminar %d for user %s not found" % (seminar.pk, email)) + print(("WARNING: seminar %d for user %s not found" % (seminar.pk, email))) diff --git a/teleforma/management/commands/teleforma-reset-all-passwords-with-mail-ae.py b/teleforma/management/commands/teleforma-reset-all-passwords-with-mail-ae.py index 54bd7d8e..2335b460 100644 --- a/teleforma/management/commands/teleforma-reset-all-passwords-with-mail-ae.py +++ b/teleforma/management/commands/teleforma-reset-all-passwords-with-mail-ae.py @@ -40,5 +40,5 @@ class Command(BaseCommand): self.init_password_email(user) profile.init_password = True profile.save() - print user.username + print(user.username) diff --git a/teleforma/management/commands/teleforma-reset-all-passwords-with-mail.py b/teleforma/management/commands/teleforma-reset-all-passwords-with-mail.py index 227955c5..60dfd88a 100644 --- a/teleforma/management/commands/teleforma-reset-all-passwords-with-mail.py +++ b/teleforma/management/commands/teleforma-reset-all-passwords-with-mail.py @@ -40,5 +40,5 @@ class Command(BaseCommand): self.init_password_email(user) profile.init_password = True profile.save() - print user.username + print(user.username) diff --git a/teleforma/management/commands/teleforma-revisions-from-bbb.py b/teleforma/management/commands/teleforma-revisions-from-bbb.py index 46fcc5b9..bf546b17 100644 --- a/teleforma/management/commands/teleforma-revisions-from-bbb.py +++ b/teleforma/management/commands/teleforma-revisions-from-bbb.py @@ -21,14 +21,14 @@ class Command(BaseCommand): def handle(self, *args, **options): if len(args) != 1 or not args[0].isdigit(): - print("Syntax: %s %s " % (sys.argv[0], - sys.argv[1])) + print(("Syntax: %s %s " % (sys.argv[0], + sys.argv[1]))) sys.exit(1) duration = int(args[0]) end = datetime.datetime.now() start = end - datetime.timedelta(seconds = duration) - print("=== Starting at %s" % end.strftime('%Y-%m-%d %H:%M:%S')) + print(("=== Starting at %s" % end.strftime('%Y-%m-%d %H:%M:%S'))) meetings = bbb.get_meetings() meetings = meetings.get_field("meetings") # no conference in BBB @@ -37,7 +37,7 @@ class Command(BaseCommand): return meetings = as_list(meetings["meeting"]) - print("=== Starting at %s" % end.strftime('%Y-%m-%d %H:%M:%S')) + print(("=== Starting at %s" % end.strftime('%Y-%m-%d %H:%M:%S'))) done = set() @@ -47,7 +47,7 @@ class Command(BaseCommand): conf = Conference.objects.get(webclass_id = meeting_id) seminar = Seminar.objects.get(conference = conf) except: - print("Warning, can't find Seminar for %s" % meeting_id) + print(("Warning, can't find Seminar for %s" % meeting_id)) continue sem_txt = "%s (%s)" % (seminar, seminar.pk) @@ -56,23 +56,23 @@ class Command(BaseCommand): user_id = str(attendee['userID']) key = (meeting_id, user_id) if key in done: - print("Warning, user %s duplicate for %s" % (user_id, sem_txt)) + print(("Warning, user %s duplicate for %s" % (user_id, sem_txt))) continue done.add(key) try: user = User.objects.get(username = user_id) except: - print("Warning, can't find user %s for seminar %s" % (user_id, sem_txt)) + print(("Warning, can't find user %s for seminar %s" % (user_id, sem_txt))) continue user_txt = "%s (%s)" % (user, user.pk) rev = SeminarRevision.objects.filter(seminar = seminar, user = user, date_modified = None) if rev.count(): - print("User %s already has an open revision on %s" % (user_txt, sem_txt)) + print(("User %s already has an open revision on %s" % (user_txt, sem_txt))) else: - print("Crediting %d seconds to %s on %s" % (duration, user_txt, sem_txt)) + print(("Crediting %d seconds to %s on %s" % (duration, user_txt, sem_txt))) sr = SeminarRevision(seminar = seminar, user = user, date = start, diff --git a/teleforma/migrations/0047_auto__del_payment__add_question__add_answer__add_seminar__add_field_do.py b/teleforma/migrations/0047_auto__del_payment__add_question__add_answer__add_seminar__add_field_do.py index a034859e..df63d0ee 100644 --- a/teleforma/migrations/0047_auto__del_payment__add_question__add_answer__add_seminar__add_field_do.py +++ b/teleforma/migrations/0047_auto__del_payment__add_question__add_answer__add_seminar__add_field_do.py @@ -27,8 +27,8 @@ class Migration(SchemaMigration): # Adding model 'Answer' db.create_table('teleforma_answer', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), - ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'answer', to=orm['auth.User'])), - ('question', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'answer', to=orm['teleforma.Question'])), + ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='answer', to=orm['auth.User'])), + ('question', self.gf('django.db.models.fields.related.ForeignKey')(related_name='answer', to=orm['teleforma.Question'])), ('answer', self.gf('django.db.models.fields.TextField')()), ('status', self.gf('django.db.models.fields.IntegerField')(default=1)), ('validated', self.gf('django.db.models.fields.BooleanField')(default=False)), diff --git a/teleforma/migrations/0049_auto__add_testimonialtemplate__add_testimonial.py b/teleforma/migrations/0049_auto__add_testimonialtemplate__add_testimonial.py index d7195cb8..55cd2fbd 100644 --- a/teleforma/migrations/0049_auto__add_testimonialtemplate__add_testimonial.py +++ b/teleforma/migrations/0049_auto__add_testimonialtemplate__add_testimonial.py @@ -13,7 +13,7 @@ class Migration(SchemaMigration): ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('organization', self.gf('django.db.models.fields.related.ForeignKey')(related_name='testimonial_template', to=orm['teleforma.Organization'])), ('text', self.gf('django.db.models.fields.TextField')()), - ('template_doc', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name=u'testimonial_template', null=True, to=orm['teleforma.Document'])), + ('template_doc', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='testimonial_template', null=True, to=orm['teleforma.Document'])), )) db.send_create_signal('teleforma', ['TestimonialTemplate']) @@ -21,8 +21,8 @@ class Migration(SchemaMigration): db.create_table('teleforma_testimonial', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('seminar', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['teleforma.Seminar'])), - ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'testimonial', to=orm['auth.User'])), - ('document', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name=u'testimonial', null=True, to=orm['teleforma.Document'])), + ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='testimonial', to=orm['auth.User'])), + ('document', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='testimonial', null=True, to=orm['teleforma.Document'])), )) db.send_create_signal('teleforma', ['Testimonial']) diff --git a/teleforma/migrations/0050_auto__add_field_testimonial_template.py b/teleforma/migrations/0050_auto__add_field_testimonial_template.py index 6fd625b7..53eb17b0 100644 --- a/teleforma/migrations/0050_auto__add_field_testimonial_template.py +++ b/teleforma/migrations/0050_auto__add_field_testimonial_template.py @@ -10,7 +10,7 @@ class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Testimonial.template' db.add_column('teleforma_testimonial', 'template', - self.gf('django.db.models.fields.related.ForeignKey')(default=1, related_name=u'testimonial', to=orm['teleforma.TestimonialTemplate']), + self.gf('django.db.models.fields.related.ForeignKey')(default=1, related_name='testimonial', to=orm['teleforma.TestimonialTemplate']), keep_default=False) def backwards(self, orm): diff --git a/teleforma/migrations/0051_auto__add_documentsimple__del_field_testimonialtemplate_template_doc__.py b/teleforma/migrations/0051_auto__add_documentsimple__del_field_testimonialtemplate_template_doc__.py index 9145bbeb..b7cd4b13 100644 --- a/teleforma/migrations/0051_auto__add_documentsimple__del_field_testimonialtemplate_template_doc__.py +++ b/teleforma/migrations/0051_auto__add_documentsimple__del_field_testimonialtemplate_template_doc__.py @@ -29,7 +29,7 @@ class Migration(SchemaMigration): # Adding field 'TestimonialTemplate.document' db.add_column('teleforma_testimonial_template', 'document', - self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name=u'testimonial_template', null=True, to=orm['teleforma.DocumentSimple']), + self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='testimonial_template', null=True, to=orm['teleforma.DocumentSimple']), keep_default=False) @@ -50,7 +50,7 @@ class Migration(SchemaMigration): # Adding field 'TestimonialTemplate.template_doc' db.add_column('teleforma_testimonial_template', 'template_doc', - self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'testimonial_template', null=True, to=orm['teleforma.Document'], blank=True), + self.gf('django.db.models.fields.related.ForeignKey')(related_name='testimonial_template', null=True, to=orm['teleforma.Document'], blank=True), keep_default=False) # Deleting field 'TestimonialTemplate.document' diff --git a/teleforma/models/__init__.py b/teleforma/models/__init__.py index da0b4b3e..f4b925e3 100644 --- a/teleforma/models/__init__.py +++ b/teleforma/models/__init__.py @@ -1,4 +1,4 @@ -from core import * -from crfpa import * -from pro import * -from ae import * \ No newline at end of file +from .core import * +from .crfpa import * +from .pro import * +from .ae import * \ No newline at end of file diff --git a/teleforma/models/core.py b/teleforma/models/core.py index b3c5a491..a70118de 100755 --- a/teleforma/models/core.py +++ b/teleforma/models/core.py @@ -499,8 +499,8 @@ class Document(MediaBase): if self.course: strings.append(self.course.code) if self.course_type.all(): - types = ' - '.join([unicode(t) for t in self.course_type.all()]) - strings.append(unicode(types)) + types = ' - '.join([str(t) for t in self.course_type.all()]) + strings.append(str(types)) if self.type: strings.append(self.type.name) strings.append(self.title) diff --git a/teleforma/models/pro.py b/teleforma/models/pro.py index c1860252..6e68ee72 100644 --- a/teleforma/models/pro.py +++ b/teleforma/models/pro.py @@ -154,7 +154,7 @@ class Seminar(ClonableMixin, Displayable, ProductCodeMixin, SuggestionsMixin): pretty_title = self.pretty_title if self.duration: from teleforma.templatetags.teleforma_tags import fancy_duration_shop_like - pretty_title += u" - Durée : %s" % (fancy_duration_shop_like(self.duration)) + pretty_title += " - Durée : %s" % (fancy_duration_shop_like(self.duration)) return pretty_title def public_url(self): @@ -244,7 +244,7 @@ class Question(ClonableMixin, models.Model): status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=3) def __unicode__(self): - return ' - '.join([unicode(self.seminar), self.title, str(self.rank)]) + return ' - '.join([str(self.seminar), self.title, str(self.rank)]) class Meta(MetaCore): db_table = app_label + '_' + 'question' @@ -265,7 +265,7 @@ class Answer(models.Model): date_added = models.DateTimeField(_('date added'), auto_now_add=True, null=True) def __unicode__(self): - return ' - '.join([unicode(self.question), self.user.username, unicode(self.date_submitted)]) + return ' - '.join([str(self.question), self.user.username, str(self.date_submitted)]) def validate(self): self.validated = True @@ -428,7 +428,7 @@ class QuizValidation(models.Model): date_validated = models.DateTimeField(_('date validated'), auto_now_add=True, null=True) def __unicode__(self): - return ' - '.join([unicode(self.quiz), self.user.username, unicode(self.date_validated)]) + return ' - '.join([str(self.quiz), self.user.username, str(self.date_validated)]) def validate(self): self.validated = True diff --git a/teleforma/templatetags/teleforma_tags.py b/teleforma/templatetags/teleforma_tags.py index e9b04025..978c642a 100644 --- a/teleforma/templatetags/teleforma_tags.py +++ b/teleforma/templatetags/teleforma_tags.py @@ -51,7 +51,7 @@ from django.conf import settings from django.template.defaultfilters import stringfilter import django.utils.timezone as timezone from django.utils.translation import ugettext_lazy as _ -from urlparse import urlparse +from urllib.parse import urlparse from docutils.core import publish_parts from django.utils.encoding import smart_str, force_unicode from django.utils.safestring import mark_safe @@ -59,7 +59,7 @@ from django.utils.safestring import mark_safe from teleforma.models.crfpa import Course from teleforma.views import get_courses from teleforma.context_processors import * -from urlparse import urlparse +from urllib.parse import urlparse register = template.Library() @@ -94,7 +94,7 @@ def value_from_settings(parser, token): # split_contents() knows not to split quoted strings. tag_name, var = token.split_contents() except ValueError: - raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] + raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0]) return ValueFromSettings(var) class ValueFromSettings(template.Node): @@ -127,10 +127,10 @@ def or_me(value, arg): Typical usage: sender|or_me:user """ - if not isinstance(value, (unicode, str)): - value = unicode(value) - if not isinstance(arg, (unicode, str)): - arg = unicode(arg) + if not isinstance(value, str): + value = str(value) + if not isinstance(arg, str): + arg = str(arg) return _('me') if value == arg else value @register.filter @@ -312,7 +312,7 @@ def preview(related): @register.filter def fancy_duration(duration): time = '' - d = unicode(duration).split(':') + d = str(duration).split(':') hours = int(d[0]) minutes = int(d[1]) if hours: @@ -329,7 +329,7 @@ def fancy_duration_shop_like(duration): if not duration: return "" time = '' - d = unicode(duration).split(':') + d = str(duration).split(':') hours = int(d[0]) minutes = int(d[1]) if hours: @@ -400,7 +400,7 @@ def current_year(): def render_flatpage(content): parsed = "" path = getattr(content, 'path', '') - if isinstance(content, basestring): + if isinstance(content, str): content = content.split("\n") for line in content: diff --git a/teleforma/utils/unicode.py b/teleforma/utils/unicode.py index f935f740..fb21d14f 100644 --- a/teleforma/utils/unicode.py +++ b/teleforma/utils/unicode.py @@ -35,10 +35,10 @@ # Author: jdunck # taken from https://github.com/jdunck/python-unicodecsv.git -import csv, codecs, cStringIO +import csv, codecs, io def _stringify(s, encoding): - if type(s)==unicode: + if type(s)==str: return s.encode(encoding) elif isinstance(s, (int , float)): pass #let csv.QUOTE_NONNUMERIC do its thing. diff --git a/teleforma/views/__init__.py b/teleforma/views/__init__.py index 1727a728..62d1035d 100644 --- a/teleforma/views/__init__.py +++ b/teleforma/views/__init__.py @@ -1,5 +1,5 @@ -from core import * -from crfpa import * -from ae import * -from pro import * -from profile import * +from .core import * +from .crfpa import * +from .ae import * +from .pro import * +from .profile import * diff --git a/teleforma/views/core.py b/teleforma/views/core.py index 48b93d56..45ab8845 100644 --- a/teleforma/views/core.py +++ b/teleforma/views/core.py @@ -36,11 +36,11 @@ import mimetypes import datetime from datetime import timedelta import random -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import json import os -import StringIO +import io import datetime from jsonrpc import jsonrpc_method @@ -81,7 +81,7 @@ from jsonrpc.proxy import ServiceProxy from teleforma.models import * from teleforma.forms import * from teleforma.context_processors import * -import pages +from . import pages import jqchat.models from xlwt import Workbook @@ -246,12 +246,12 @@ class CourseListView(ListView): @jsonrpc_method('teleforma.get_dep_courses') def get_dep_courses(request, id): department = Department.objects.get(id=id) - return [{'id': str(c.id), 'name': unicode(c)} for c in department.course.all()] + return [{'id': str(c.id), 'name': str(c)} for c in department.course.all()] @jsonrpc_method('teleforma.get_dep_periods') def get_dep_periods(request, id): department = Department.objects.get(id=id) - return [{'id': str(c.id), 'name': unicode(c)} for c in department.period.all()] + return [{'id': str(c.id), 'name': str(c)} for c in department.period.all()] class CourseView(DetailView): @@ -289,9 +289,9 @@ class CourseView(DetailView): media_list = [] for media in course.media.all(): if media.is_published and media.file and media.conference and 'video' in media.mime_type: - urls = [ {'url': settings.MEDIA_URL + unicode(media.file), 'mime_type': media.mime_type} ] + urls = [ {'url': settings.MEDIA_URL + str(media.file), 'mime_type': media.mime_type} ] for transcoded in media.transcoded.all(): - urls.append({'url':settings.MEDIA_URL + unicode(transcoded.file), 'mime_type': transcoded.mime_type}) + urls.append({'url':settings.MEDIA_URL + str(transcoded.file), 'mime_type': transcoded.mime_type}) media_list.append({'session': media.conference.session, 'urls': urls, 'poster': media.poster_url()}) return media_list @@ -548,7 +548,7 @@ class ConferenceView(DetailView): context['seminar'] = None context['record'] = None # debug -> test links - context['range'] = range(0,15) + context['range'] = list(range(0,15)) webclass_status = "" now = datetime.datetime.now() @@ -718,7 +718,7 @@ class ConferenceRecordView(FormView): def snapshot(self, url, dir): width = 160 height = 90 - img = urllib.urlopen(url) + img = urllib.request.urlopen(url) path = dir + os.sep + 'preview.webp' f = open(path, 'w') f.write(img.read()) @@ -778,7 +778,7 @@ class ConferenceRecordView(FormView): stream_type=stream_type, streaming=True) stream.save() else: - raise 'Error : Bad Conference dictionnary' + raise Exception('Error : Bad Conference dictionnary') def push(self, conference): url = 'http://' + conference.department.domain + '/json/' diff --git a/teleforma/views/crfpa.py b/teleforma/views/crfpa.py index 5e57d9cf..6e8ac78e 100644 --- a/teleforma/views/crfpa.py +++ b/teleforma/views/crfpa.py @@ -203,7 +203,7 @@ class UsersCourseView(UsersView): def get_course_code(obj): if obj: - return unicode(obj.code) + return str(obj.code) else: return '' @@ -219,11 +219,11 @@ class UsersXLSExport(object): row.write(0, user.last_name) row.write(1, user.first_name) row.write(9, user.email) - row.write(2, unicode(student.iej)) + row.write(2, str(student.iej)) code = student.training.code if student.platform_only: code = 'I - ' + code - row.write(3, unicode(code)) + row.write(3, str(code)) row.write(4, get_course_code(student.procedure)) row.write(5, get_course_code(student.written_speciality)) row.write(6, get_course_code(student.oral_speciality)) diff --git a/teleforma/views/home.py b/teleforma/views/home.py index b549b43c..806ec41c 100644 --- a/teleforma/views/home.py +++ b/teleforma/views/home.py @@ -34,7 +34,7 @@ # Authors: Olivier Guilyardi # Guillaume Pellerin -import pages +from . import pages from django.shortcuts import render, redirect from django.contrib import auth from django.http import HttpResponse diff --git a/teleforma/views/pro.py b/teleforma/views/pro.py index 75f74b62..f011e7bd 100644 --- a/teleforma/views/pro.py +++ b/teleforma/views/pro.py @@ -37,8 +37,6 @@ from teleforma.views.core import * from teleforma.context_processors import * from django.core.exceptions import PermissionDenied -from teleforma.utils.unicode import UnicodeWriter - from django.utils.translation import ugettext_lazy as _ from django.template import loader, Context, RequestContext from django.views.generic.base import TemplateResponseMixin @@ -54,7 +52,7 @@ from django.template.loader import render_to_string import os, datetime from cgi import escape -from cStringIO import StringIO +from io import StringIO import weasyprint @@ -481,7 +479,7 @@ class AnswersView(ListView): testimonial.save() # url = reverse('teleforma-seminar-testimonial-download', kwargs={'pk':seminar.id}) + '?format=pdf' text = render_to_string('teleforma/messages/seminar_validated.txt', context) - subject = seminar.title + ' : ' + unicode(_('all your answers has been validated')) + subject = seminar.title + ' : ' + str(_('all your answers has been validated')) else: text = render_to_string('teleforma/messages/answer_validated.txt', context) @@ -537,7 +535,7 @@ class AnswersView(ListView): sender = request.user text = render_to_string('teleforma/messages/answer_rejected.txt', context) - subject = seminar.title + ' : ' + unicode(_('validation conditions for an answer')) + subject = seminar.title + ' : ' + str(_('validation conditions for an answer')) mess = Message(sender=sender, recipient=user, subject=subject, body=text) mess.moderation_status = 'a' mess.save() @@ -728,7 +726,7 @@ class PDFTemplateResponseMixin(TemplateResponseMixin): """ if self.pdf_template_name is None: names = super(PDFTemplateResponseMixin, self).get_template_names() - return map(self._get_pdf_template_name, names) + return list(map(self._get_pdf_template_name, names)) return [self.pdf_template_name] def get_pdf_filename(self): @@ -805,7 +803,7 @@ class TestimonialDownloadView(TestimonialView): def get_pdf_filename(self): super(TestimonialDownloadView, self).get_pdf_filename() seminar = self.get_object() - prefix = unicode(_('Testimonial')) + prefix = str(_('Testimonial')) filename = '_'.join([prefix, seminar.title.replace(',', ' '), self.request.user.first_name, self.request.user.last_name,]) filename += '.pdf' @@ -966,13 +964,13 @@ def process_webclass_bbb_webhook(request, event): mixin = SeminarRevisionMixin() if event["id"] == "user-joined": - print("JOIN", seminar, conf, user) + print(("JOIN", seminar, conf, user)) mixin.seminar_do_load(request, seminar.pk, user.username) - print("JOIN DONE", seminar, conf, user) + print(("JOIN DONE", seminar, conf, user)) else: - print("LEAVE", seminar, conf, user) + print(("LEAVE", seminar, conf, user)) mixin.seminar_do_unload(request, seminar.pk, user.username) - print("LEAVE DONE", seminar, conf, user) + print(("LEAVE DONE", seminar, conf, user)) @csrf_exempt def webclass_bbb_webhook(request): @@ -989,7 +987,7 @@ def webclass_bbb_webhook(request): event = event[0]["data"] if event["type"] != "event": raise PermissionDenied - print(event["id"]) + print((event["id"])) if event["id"] not in ('user-joined', 'user-left'): return HttpResponse("ok") -- 2.39.5