Unverified Commit 78a96034 authored by Thom Wiggers's avatar Thom Wiggers 📐
Browse files

Format looots of code

parent 02055acc
...@@ -19,9 +19,9 @@ class MemberGroupMembershipInlineFormSet(forms.BaseInlineFormSet): ...@@ -19,9 +19,9 @@ class MemberGroupMembershipInlineFormSet(forms.BaseInlineFormSet):
""" """
Solely here for performance reasons. Solely here for performance reasons.
Needed because the `__str__()` of `MemberGroupMembership` (which is displayed Needed because the `__str__()` of `MemberGroupMembership` (which is
above each inline form) uses the username, name of the member and name of displayed above each inline form) uses the username, name of the member
the group. and name of the group.
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
...@@ -40,28 +40,6 @@ class MemberGroupMembershipInline(admin.StackedInline): ...@@ -40,28 +40,6 @@ class MemberGroupMembershipInline(admin.StackedInline):
autocomplete_fields = ('member',) autocomplete_fields = ('member',)
@admin.register(models.Committee)
class CommitteeAdmin(TranslatedModelAdmin):
"""Manage the committees"""
inlines = (MemberGroupMembershipInline,)
form = MemberGroupForm
list_display = ('name', 'since', 'until', 'active', 'email')
list_filter = ('until', 'active',)
search_fields = ('name', 'description')
filter_horizontal = ('permissions',)
fields = ('name', 'description', 'photo', 'permissions', 'since',
'until', 'contact_mailinglist', 'contact_email',
'wiki_namespace', 'active')
def email(self, instance):
if instance.contact_email:
return instance.contact_email
elif instance.contact_mailinglist:
return instance.contact_mailinglist.name + '@thalia.nu'
return None
@admin.register(models.Society) @admin.register(models.Society)
class CommitteeAdmin(TranslatedModelAdmin): class CommitteeAdmin(TranslatedModelAdmin):
"""Manage the societies""" """Manage the societies"""
......
...@@ -31,7 +31,8 @@ def membergroup_member_card(membership): ...@@ -31,7 +31,8 @@ def membergroup_member_card(membership):
if 'since' in membership: if 'since' in membership:
since_text = _('Committee member since: ') + '?' since_text = _('Committee member since: ') + '?'
if membership['since'].year > 1970: if membership['since'].year > 1970:
since_text = _('Committee member since: ') + str(membership['since'].year) since_text = _('Committee member since: {}').format(
membership['since'].year)
meta_text += '<p class="px-1">{}</p>'.format(since_text) meta_text += '<p class="px-1">{}</p>'.format(since_text)
if 'role' in membership and membership['role']: if 'role' in membership and membership['role']:
meta_text += '<p class="px-1">{}</p>'.format(membership['role']) meta_text += '<p class="px-1">{}</p>'.format(membership['role'])
......
...@@ -59,25 +59,26 @@ class CommitteeMembersTest(TestCase): ...@@ -59,25 +59,26 @@ class CommitteeMembersTest(TestCase):
m1 = MemberGroupMembership(group=self.testcie, m1 = MemberGroupMembership(group=self.testcie,
member=self.testuser, member=self.testuser,
since=timezone.now().date().replace( since=timezone.now().date().replace(
year=2014, month=1, day=1), year=2014, month=1, day=1),
until=timezone.now().date().replace( until=timezone.now().date().replace(
year=2014, month=3, day=1)) year=2014, month=3, day=1))
m1.save() m1.save()
m2 = MemberGroupMembership(group=self.testcie, m2 = MemberGroupMembership(group=self.testcie,
member=self.testuser, member=self.testuser,
since=timezone.now().date().replace( since=timezone.now().date().replace(
year=2014, month=1, day=1), year=2014, month=1, day=1),
until=timezone.now().date().replace( until=timezone.now().date().replace(
year=2014, month=2, day=1)) year=2014, month=2, day=1))
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
m2.full_clean() m2.full_clean()
def test_until_date(self): def test_until_date(self):
m = MemberGroupMembership(group=self.testcie, m = MemberGroupMembership(
member=self.testuser, group=self.testcie,
until=timezone.now().date().replace(year=2000), member=self.testuser,
chair=False) until=timezone.now().date().replace(year=2000),
chair=False)
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
m.clean() m.clean()
m.since = timezone.now().date().replace(year=1900) m.since = timezone.now().date().replace(year=1900)
......
...@@ -2,8 +2,7 @@ from django.shortcuts import get_object_or_404, render, redirect, reverse ...@@ -2,8 +2,7 @@ from django.shortcuts import get_object_or_404, render, redirect, reverse
import datetime import datetime
from utils.snippets import datetime_to_lectureyear from utils.snippets import datetime_to_lectureyear
from utils.translation import localize_attr_name from utils.translation import localize_attr_name
from .models import Board, MemberGroup, MemberGroupMembership, Committee, \ from .models import Board, MemberGroupMembership, Committee, Society
Society
def committee_index(request): def committee_index(request):
......
...@@ -185,7 +185,10 @@ class EventRetrieveSerializer(serializers.ModelSerializer): ...@@ -185,7 +185,10 @@ class EventRetrieveSerializer(serializers.ModelSerializer):
return instance.is_pizza_event() return instance.is_pizza_event()
def _google_maps_url(self, instance): def _google_maps_url(self, instance):
return create_google_maps_url(instance.map_location, zoom=13, size='450x250') return create_google_maps_url(
instance.map_location,
zoom=13,
size='450x250')
class EventListSerializer(serializers.ModelSerializer): class EventListSerializer(serializers.ModelSerializer):
......
...@@ -33,7 +33,8 @@ def _extract_date(param): ...@@ -33,7 +33,8 @@ def _extract_date(param):
if param is None: if param is None:
return None return None
try: try:
return timezone.make_aware(datetime.strptime(param, '%Y-%m-%dT%H:%M:%S')) return timezone.make_aware(
datetime.strptime(param, '%Y-%m-%dT%H:%M:%S'))
except ValueError: except ValueError:
return timezone.make_aware(datetime.strptime(param, '%Y-%m-%d')) return timezone.make_aware(datetime.strptime(param, '%Y-%m-%d'))
...@@ -161,7 +162,8 @@ class EventViewset(viewsets.ReadOnlyModelViewSet): ...@@ -161,7 +162,8 @@ class EventViewset(viewsets.ReadOnlyModelViewSet):
queryset, many=True, context={'member': request.member}) queryset, many=True, context={'member': request.member})
return Response(serializer.data) return Response(serializer.data)
@action(detail=False, permission_classes=(IsAdminUser, UnpublishedEventPermissions,)) @action(detail=False,
permission_classes=(IsAdminUser, UnpublishedEventPermissions,))
def unpublished(self, request): def unpublished(self, request):
""" """
Defines a custom route that outputs the correctly formatted Defines a custom route that outputs the correctly formatted
......
...@@ -330,8 +330,8 @@ class Event(models.Model, metaclass=ModelTranslateMeta): ...@@ -330,8 +330,8 @@ class Event(models.Model, metaclass=ModelTranslateMeta):
start_reminder.save() start_reminder.save()
self.start_reminder = start_reminder self.start_reminder = start_reminder
if self.registration_required: if self.registration_required:
self.start_reminder.users.set(self.participants.values_list( self.start_reminder.users.set(
'member', flat=True)) self.participants.values_list('member', flat=True))
else: else:
self.start_reminder.users.set(Member.current_members.all()) self.start_reminder.users.set(Member.current_members.all())
elif start_reminder.pk is not None: elif start_reminder.pk is not None:
......
...@@ -36,8 +36,10 @@ def get_automatic_lists(): ...@@ -36,8 +36,10 @@ def get_automatic_lists():
['leden', 'members'], '[THALIA]', ['leden', 'members'], '[THALIA]',
Member.all_with_membership('member'), True, True, True) Member.all_with_membership('member'), True, True, True)
lists += _create_automatic_list( lists += _create_automatic_list(
['begunstigers', 'benefactors'], '[THALIA]', Member.all_with_membership( ['begunstigers', 'benefactors'],
Membership.BENEFACTOR), multilingual=True) '[THALIA]',
Member.all_with_membership(Membership.BENEFACTOR),
multilingual=True)
lists += _create_automatic_list( lists += _create_automatic_list(
['ereleden', 'honorary'], '[THALIA]', Member.all_with_membership( ['ereleden', 'honorary'], '[THALIA]', Member.all_with_membership(
'honorary'), multilingual=True) 'honorary'), multilingual=True)
......
...@@ -138,7 +138,9 @@ class MemberListSerializer(serializers.ModelSerializer): ...@@ -138,7 +138,9 @@ class MemberListSerializer(serializers.ModelSerializer):
def _photo(self, instance): def _photo(self, instance):
if instance.profile.photo: if instance.profile.photo:
return self.context['request'].build_absolute_uri( return self.context['request'].build_absolute_uri(
thumbnail(instance.profile.photo, settings.THUMBNAIL_SIZES['medium'], 1)) thumbnail(instance.profile.photo,
settings.THUMBNAIL_SIZES['medium'],
1))
else: else:
return self.context['request'].build_absolute_uri( return self.context['request'].build_absolute_uri(
static('members/images/default-avatar.jpg')) static('members/images/default-avatar.jpg'))
......
...@@ -20,7 +20,8 @@ def _extract_date(param): ...@@ -20,7 +20,8 @@ def _extract_date(param):
if param is None: if param is None:
return None return None
try: try:
return timezone.make_aware(datetime.strptime(param, '%Y-%m-%dT%H:%M:%S')) return timezone.make_aware(
datetime.strptime(param, '%Y-%m-%dT%H:%M:%S'))
except ValueError: except ValueError:
return timezone.make_aware(datetime.strptime(param, '%Y-%m-%d')) return timezone.make_aware(datetime.strptime(param, '%Y-%m-%d'))
......
...@@ -13,11 +13,13 @@ register = template.Library() ...@@ -13,11 +13,13 @@ register = template.Library()
@register.inclusion_tag('includes/grid_item.html') @register.inclusion_tag('includes/grid_item.html')
def member_card(member, meta_text=None, ribbon=None): def member_card(member, meta_text=None, ribbon=None):
if meta_text is None and member.profile.starting_year: if meta_text is None and member.profile.starting_year:
meta_text = '<p class="px-1">{}: {}</p>'.format(_('Cohort'), member.profile.starting_year) meta_text = '<p class="px-1">{}: {}</p>'.format(
_('Cohort'), member.profile.starting_year)
image_url = static('members/images/default-avatar.jpg') image_url = static('members/images/default-avatar.jpg')
if member.profile.photo: if member.profile.photo:
image_url = thumbnail(member.profile.photo, settings.THUMBNAIL_SIZES['medium']) image_url = thumbnail(member.profile.photo,
settings.THUMBNAIL_SIZES['medium'])
return grid_item( return grid_item(
title=member.profile.display_name(), title=member.profile.display_name(),
......
...@@ -5,12 +5,15 @@ from pytz.exceptions import InvalidTimeError ...@@ -5,12 +5,15 @@ from pytz.exceptions import InvalidTimeError
from rest_framework import viewsets, filters from rest_framework import viewsets, filters
from rest_framework.decorators import action from rest_framework.decorators import action
from rest_framework.exceptions import ParseError from rest_framework.exceptions import ParseError
from rest_framework.permissions import IsAuthenticatedOrReadOnly, \ from rest_framework.permissions import (
IsAuthenticated IsAuthenticatedOrReadOnly, IsAuthenticated
)
from rest_framework.response import Response from rest_framework.response import Response
from partners.api.serializers import PartnerEventCalendarJSSerializer, \ from partners.api.serializers import (
PartnerEventSerializer, PartnerSerializer PartnerEventCalendarJSSerializer, PartnerEventSerializer,
PartnerSerializer
)
from partners.models import Partner, PartnerEvent from partners.models import Partner, PartnerEvent
...@@ -19,7 +22,8 @@ def _extract_date(param): ...@@ -19,7 +22,8 @@ def _extract_date(param):
if param is None: if param is None:
return None return None
try: try:
return timezone.make_aware(datetime.strptime(param, '%Y-%m-%dT%H:%M:%S')) return timezone.make_aware(
datetime.strptime(param, '%Y-%m-%dT%H:%M:%S'))
except ValueError: except ValueError:
return timezone.make_aware(datetime.strptime(param, '%Y-%m-%d')) return timezone.make_aware(datetime.strptime(param, '%Y-%m-%d'))
......
...@@ -100,11 +100,13 @@ class PaymentAdminViewTest(TestCase): ...@@ -100,11 +100,13 @@ class PaymentAdminViewTest(TestCase):
'/admin/payments/payment/%s/change/' % self.payment.pk '/admin/payments/payment/%s/change/' % self.payment.pk
) )
process_payment.assert_called_once_with(payment_qs, payment_type) process_payment.assert_called_once_with(
payment_qs, payment_type)
messages_success.assert_called_once_with( messages_success.assert_called_once_with(
response.wsgi_request, _('Successfully processed %s.') % response.wsgi_request,
model_ngettext(self.payment, 1) _('Successfully processed %s.') %
model_ngettext(self.payment, 1)
) )
with self.subTest('Send post with failed processing'): with self.subTest('Send post with failed processing'):
...@@ -115,6 +117,7 @@ class PaymentAdminViewTest(TestCase): ...@@ -115,6 +117,7 @@ class PaymentAdminViewTest(TestCase):
}) })
messages_error.assert_called_once_with( messages_error.assert_called_once_with(
response.wsgi_request, _('Could not process %s.') % response.wsgi_request,
model_ngettext(self.payment, 1) _('Could not process %s.') %
model_ngettext(self.payment, 1)
) )
...@@ -20,5 +20,3 @@ class PaymentWidget(Widget): ...@@ -20,5 +20,3 @@ class PaymentWidget(Widget):
context['url'] = payment.get_admin_url() context['url'] = payment.get_admin_url()
context['processed'] = payment.processed context['processed'] = payment.processed
return context return context
...@@ -3,7 +3,6 @@ import os ...@@ -3,7 +3,6 @@ import os
import random import random
import logging import logging
from PIL.JpegImagePlugin import JpegImageFile
from django.conf import settings from django.conf import settings
from django.db import models from django.db import models
from django.urls import reverse from django.urls import reverse
......
from io import BytesIO from io import BytesIO
from zipfile import ZipFile from zipfile import ZipFile
from django.test import Client, TestCase, RequestFactory from django.test import Client, TestCase
from members.models import Member from members.models import Member
from photos.models import Album, Photo from photos.models import Album, Photo
......
...@@ -127,7 +127,6 @@ class AlbumTest(TestCase): ...@@ -127,7 +127,6 @@ class AlbumTest(TestCase):
since=date(year=2015, month=1, day=1), since=date(year=2015, month=1, day=1),
until=None) until=None)
for i in range(10): for i in range(10):
with open("photos/fixtures/thom_assessor.png", "rb") as f: with open("photos/fixtures/thom_assessor.png", "rb") as f:
fi = SimpleUploadedFile(name='photo{}.png'.format(i), fi = SimpleUploadedFile(name='photo{}.png'.format(i),
...@@ -150,7 +149,7 @@ class AlbumTest(TestCase): ...@@ -150,7 +149,7 @@ class AlbumTest(TestCase):
until=date(year=2018, month=1, day=1)) until=date(year=2018, month=1, day=1))
with self.subTest(): with self.subTest():
self.album.date=date(year=2017, month=1, day=1) self.album.date = date(year=2017, month=1, day=1)
self.album.save() self.album.save()
response = self.client.get(reverse( response = self.client.get(reverse(
...@@ -158,7 +157,7 @@ class AlbumTest(TestCase): ...@@ -158,7 +157,7 @@ class AlbumTest(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
with self.subTest(): with self.subTest():
self.album.date=date(year=2018, month=9, day=5) self.album.date = date(year=2018, month=9, day=5)
self.album.save() self.album.save()
response = self.client.get(reverse( response = self.client.get(reverse(
......
...@@ -5,7 +5,6 @@ from django.forms import Field ...@@ -5,7 +5,6 @@ from django.forms import Field
from django.utils.html import format_html from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from members.models import Membership
from payments.widgets import PaymentWidget from payments.widgets import PaymentWidget
from . import services from . import services
from .models import Entry, Registration, Renewal from .models import Entry, Registration, Renewal
...@@ -89,7 +88,8 @@ class RegistrationAdmin(admin.ModelAdmin): ...@@ -89,7 +88,8 @@ class RegistrationAdmin(admin.ModelAdmin):
request.user.has_perm('registrations.review_entries')): request.user.has_perm('registrations.review_entries')):
obj = Entry.objects.get(id=object_id) obj = Entry.objects.get(id=object_id)
can_review = obj.status == Entry.STATUS_REVIEW can_review = obj.status == Entry.STATUS_REVIEW
can_revert = obj.status in [Entry.STATUS_ACCEPTED, Entry.STATUS_REJECTED] can_revert = obj.status in [
Entry.STATUS_ACCEPTED, Entry.STATUS_REJECTED]
try: try:
can_resend = obj.registration.status == Entry.STATUS_CONFIRM can_resend = obj.registration.status == Entry.STATUS_CONFIRM
except Registration.DoesNotExist: except Registration.DoesNotExist:
......
...@@ -4,7 +4,6 @@ from django.forms import TypedChoiceField ...@@ -4,7 +4,6 @@ from django.forms import TypedChoiceField
from django.utils import timezone from django.utils import timezone
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from payments.widgets import PaymentWidget
from utils.snippets import datetime_to_lectureyear from utils.snippets import datetime_to_lectureyear
from .models import Registration, Renewal from .models import Registration, Renewal
......
...@@ -107,7 +107,7 @@ class EntryAdminViewTest(TestCase): ...@@ -107,7 +107,7 @@ class EntryAdminViewTest(TestCase):
@mock.patch('registrations.services.accept_entries') @mock.patch('registrations.services.accept_entries')
@mock.patch('registrations.services.reject_entries') @mock.patch('registrations.services.reject_entries')
def test_post_accept(self, reject_entries, accept_entries, def test_post_accept(self, reject_entries, accept_entries,
check_unique_user): check_unique_user):
self.view.action = 'accept' self.view.action = 'accept'
for type, entry in { for type, entry in {
'registration': self.entry1, 'registration': self.entry1,
...@@ -215,7 +215,8 @@ class EntryAdminViewTest(TestCase): ...@@ -215,7 +215,8 @@ class EntryAdminViewTest(TestCase):
entry_qs = Entry.objects.filter(pk=entry.pk) entry_qs = Entry.objects.filter(pk=entry.pk)
send_email.reset_mock() send_email.reset_mock()
send_email.return_value = None send_email.return_value = None
with mock.patch('registrations.models.Entry.objects.filter') as qs_mock: with mock.patch(
'registrations.models.Entry.objects.filter') as qs_mock:
qs_mock.return_value = entry_qs qs_mock.return_value = entry_qs
qs_mock.get = Mock(return_value=entry_qs.get()) qs_mock.get = Mock(return_value=entry_qs.get())
...@@ -246,7 +247,8 @@ class EntryAdminViewTest(TestCase): ...@@ -246,7 +247,8 @@ class EntryAdminViewTest(TestCase):
entry_qs = Entry.objects.filter(pk=entry.pk) entry_qs = Entry.objects.filter(pk=entry.pk)
revert.reset_mock() revert.reset_mock()
revert.return_value = None revert.return_value = None
with mock.patch('registrations.models.Entry.objects.filter') as qs_mock: with mock.patch(
'registrations.models.Entry.objects.filter') as qs_mock:
qs_mock.return_value = entry_qs qs_mock.return_value = entry_qs
qs_mock.get = Mock(return_value=entry_qs.get()) qs_mock.get = Mock(return_value=entry_qs.get())
...@@ -367,7 +369,7 @@ class ConfirmEmailViewTest(TestCase): ...@@ -367,7 +369,7 @@ class ConfirmEmailViewTest(TestCase):
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, '/registration/register/') self.assertEqual(response.url, '/registration/register/')
with self.subTest('Redirect when registration confirm gives error'): with self.subTest('Redirect when registration confirm errors'):
confirm_entry.side_effect = ValidationError(message='Error') confirm_entry.side_effect = ValidationError(message='Error')
response = self.client.get(reverse( response = self.client.get(reverse(
...@@ -472,7 +474,8 @@ class RenewalFormViewTest(TestCase): ...@@ -472,7 +474,8 @@ class RenewalFormViewTest(TestCase):
) )
self.view.request = MagicMock() self.view.request = MagicMock()
with mock.patch('members.models.Membership.objects') as qs_mock: with mock.patch('members.models.Membership.objects'
) as _qs: # noqa: F841
Membership.objects.filter().exists.return_value = True Membership.objects.filter().exists.return_value = True
context = self.view.get_context_data(form=MagicMock()) context = self.view.get_context_data(form=MagicMock())
self.assertEqual(len(context), 8) self.assertEqual(len(context), 8)
...@@ -557,7 +560,8 @@ class RenewalFormViewTest(TestCase): ...@@ -557,7 +560,8 @@ class RenewalFormViewTest(TestCase):
request = super_post.call_args[0][0] request = super_post.call_args[0][0]
self.assertEqual(request.POST['member'], 2) self.assertEqual(request.POST['member'], 2)
self.assertEqual(request.POST['membership_type'], Membership.BENEFACTOR) self.assertEqual(request.POST['membership_type'],
Membership.BENEFACTOR)
self.assertEqual(request.POST['length'], Entry.MEMBERSHIP_YEAR) self.assertEqual(request.POST['length'], Entry.MEMBERSHIP_YEAR)
@mock.patch('registrations.emails.send_new_renewal_board_message') @mock.patch('registrations.emails.send_new_renewal_board_message')
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment