Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django 3.2 upgrade #667

Merged
merged 22 commits into from Sep 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 7 additions & 10 deletions applications/admin.py
@@ -1,8 +1,7 @@
from adminsortable2.admin import SortableAdminMixin
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import redirect, render
from django.urls import reverse
from django.urls import reverse, path
from django.utils.html import format_html

from core.models import Event
Expand All @@ -18,7 +17,7 @@ class FormAdmin(admin.ModelAdmin):
)

def get_queryset(self, request):
qs = super(FormAdmin, self).get_queryset(request)
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(event__team__in=[request.user])
Expand All @@ -31,10 +30,9 @@ def get_form(self, request, obj=None, **kwargs):
return form

def get_urls(self):
urls = super(FormAdmin, self).get_urls()
urls = super().get_urls()
my_urls = [
url(r'submissions/$',
self.admin_site.admin_view(self.view_submissions)),
path('submissions/', self.admin_site.admin_view(self.view_submissions)),
]
return my_urls + urls

Expand Down Expand Up @@ -77,13 +75,13 @@ class QuestionAdmin(SortableAdminMixin, admin.ModelAdmin):
list_filter = (FormFilter,)

def get_queryset(self, request):
qs = super(QuestionAdmin, self).get_queryset(request)
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(form__event__team__in=[request.user])

def get_form(self, request, obj=None, **kwargs):
form = super(QuestionAdmin, self).get_form(request, obj, **kwargs)
form = super().get_form(request, obj, **kwargs)
if not request.user.is_superuser:
form_objs = Form.objects.filter(event__team__in=[request.user])
form.base_fields['form'].queryset = form_objs
Expand All @@ -109,8 +107,7 @@ class AnswerAdmin(admin.ModelAdmin):


class EmailAdmin(admin.ModelAdmin):
list_display = ('form', 'author', 'subject', 'recipients_group', 'created',
'sent')
list_display = ('form', 'author', 'subject', 'recipients_group', 'created', 'sent')


admin.site.register(Form, FormAdmin)
Expand Down
38 changes: 18 additions & 20 deletions applications/forms.py
Expand Up @@ -23,13 +23,14 @@ def __init__(self, *args, **kwargs):
self.base_fields = generate_form_from_questions(
self.form.question_set.all()
)
self.base_fields.update({
'captcha': BetterReCaptchaField()
})
super(ApplicationForm, self).__init__(*args, **kwargs)
if not settings.RECAPTCHA_TESTING:
self.base_fields.update({
'captcha': BetterReCaptchaField()
})
super().__init__(*args, **kwargs)

def clean(self):
cleaned_data = self.cleaned_data
cleaned_data = super().clean()

question = Question.objects.filter(
form=self.form,
Expand All @@ -39,17 +40,13 @@ def clean(self):
if not question:
return cleaned_data

field_name = 'question_{}'.format(question.pk)
field_name = f'question_{question.pk}'
email = self.cleaned_data.get(field_name)

if email is not None:
if (Application.objects
.filter(form=self.form, email=email)
.exists()):
self.add_error(
field_name,
_('Application for this e-mail already exists.')
)
existing_application = Application.objects.filter(form=self.form, email=email)
if existing_application.exists():
self.add_error(field_name, _('Application for this e-mail already exists.'))

# Always return cleaned_data
return cleaned_data
Expand Down Expand Up @@ -87,14 +84,14 @@ def save(self, *args, **kwargs):
if not self.form.event.email:
# If event doesn't have an email (legacy events), create
# it just by taking the url. In 99% cases, it is correct.
self.form.event.email = "{}@djangogirls.org".format(
self.form.event.page_url)
self.form.event.email = f"{self.form.event.page_url}@djangogirls.org"
self.form.event.save()

if application.email:
# Send confirmation email
subject = "Confirmation of your application for {}".format(
self.form.event.page_title)
subject = _("Confirmation of your application for %(page_title)s") % {
'page_title': self.form.event.page_title
}
body = render_to_string(
'emails/application_confirmation.html',
{
Expand Down Expand Up @@ -123,8 +120,9 @@ def save(self, *args, **kwargs):
url = "https://us8.api.mailchimp.com/3.0/lists/d278270e6f/members/"
payload = {"email_address": application.email,
"status": "pending"}
requests.post(url, auth=(
'user', settings.MAILCHIMP_API_KEY), json=payload)
requests.post(
url, auth=('user', settings.MAILCHIMP_API_KEY), json=payload
)


class ScoreForm(forms.ModelForm):
Expand All @@ -140,7 +138,7 @@ def __init__(self, *args, **kwargs):
"""
When email is already sent, the form should be disabled
"""
super(EmailForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
if self.instance.sent:
# email was sent, let's disable all fields:
for field in self.fields:
Expand Down
43 changes: 43 additions & 0 deletions applications/migrations/0005_auto_20210906_0915.py
@@ -0,0 +1,43 @@
# Generated by Django 3.2.7 on 2021-09-06 09:15

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('applications', '0004_add_on_delete'),
]

operations = [
migrations.AlterField(
model_name='answer',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='application',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='email',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='form',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='question',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='score',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
12 changes: 5 additions & 7 deletions applications/models.py
Expand Up @@ -55,11 +55,11 @@ class Form(models.Model):
null=True, verbose_name=_("Application process is open until"))

def __str__(self):
return 'Application form for {}'.format(self.event.name)
return f'Application form for {self.event.name}'

def save(self, *args, **kwargs):
is_form_new = False if self.pk else True
super(Form, self).save(*args, **kwargs)
super().save(*args, **kwargs)

if is_form_new:
self.create_default_questions()
Expand All @@ -79,7 +79,7 @@ def number_of_applications(self):
@property
def application_open(self):
if self.open_from and self.open_until:
return (self.open_from < timezone.now() < self.open_until)
return self.open_from < timezone.now() < self.open_until
return True


Expand Down Expand Up @@ -344,7 +344,7 @@ def __str__(self):
return self.subject

def get_rsvp_link(self, code):
return 'http://djangogirls.org/{}/rsvp/{}'.format(self.form.event.page_url, code)
return f'http://djangogirls.org/{self.form.event.page_url}/rsvp/{code}'

def add_rsvp_links(self, body, application):
body = body.replace('[rsvp-url-yes]', self.get_rsvp_link(application.get_rsvp_yes_code()))
Expand All @@ -366,9 +366,7 @@ def send(self):
recipients = self.get_applications()
self.number_of_recipients = recipients.count()
self.sent_from = (
self.form.event.email or '{}@djangogirls.org'.format(
self.form.event.page_url
)
self.form.event.email or f'{self.form.event.page_url}@djangogirls.org'
)
successfuly_sent = []
failed_to_sent = []
Expand Down
2 changes: 1 addition & 1 deletion applications/questions.py
Expand Up @@ -32,7 +32,7 @@ def generate_form_from_questions(questions):
'help_text': question.help_text or None,
'required': question.is_required,
}
name = 'question_{}'.format(question.pk)
name = f'question_{question.pk}'

if question.question_type == 'text':
options['widget'] = forms.Textarea
Expand Down
6 changes: 3 additions & 3 deletions applications/templatetags/applications_tags.py
Expand Up @@ -7,10 +7,10 @@
@register.simple_tag
def display_sorting_arrow(name, current_order):
is_reversed = False
if '-{}'.format(name) == current_order:
if f'-{name}' == current_order:
is_reversed = True

if is_reversed:
return mark_safe('<a href="?order={}">▼</a>'.format(name))
return mark_safe(f'<a href="?order={name}">▼</a>')
else:
return mark_safe('<a href="?order=-{}">▲</a>'.format(name))
return mark_safe(f'<a href="?order=-{name}">▲</a>')
42 changes: 24 additions & 18 deletions applications/views.py
Expand Up @@ -58,7 +58,8 @@ def apply(request, city):
})

number_of_email_questions = Question.objects.filter(
question_type='email', form=form_obj).count()
question_type='email', form=form_obj
).count()

return render(request, 'applications/apply.html', {
'event': event,
Expand Down Expand Up @@ -112,11 +113,11 @@ def applications_csv(request, city):
try:
applications = get_applications_for_event(
event, state, rsvp_status, order)
except:
except: # TODO: what's the exception here?
return redirect('core:event', city=city)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = (
'attachment; filename="{}.csv"'.format(city)
f'attachment; filename="{city}.csv"'
)
writer = csv.writer(response)
csv_header = [
Expand Down Expand Up @@ -150,11 +151,12 @@ def application_detail(request, city, app_number):
Display the details of a single application.
"""
application = get_object_or_404(
Application, form__event__page_url=city, number=app_number)

Application, form__event__page_url=city, number=app_number
)
try:
score = Score.objects.get(
user=request.user, application=application)
user=request.user, application=application
)
except Score.DoesNotExist:
score = None
score_form = ScoreForm(instance=score)
Expand All @@ -175,7 +177,8 @@ def application_detail(request, city, app_number):
new_app = get_random_application(request.user, event, application)
if new_app:
return redirect(
'applications:application_detail', city, new_app.number)
'applications:application_detail', city, new_app.number
)
return redirect('applications:applications', city)

return render(request, 'applications/application_detail.html', {
Expand Down Expand Up @@ -213,7 +216,8 @@ def compose_email(request, city, email_id=None):
event = get_event(city, request.user.is_authenticated, False)
form_obj = get_object_or_404(Form, event=event)
emailmsg = None if not email_id else get_object_or_404(
Email, form__event=event, id=email_id)
Email, form__event=event, id=email_id
)

form = EmailForm(request.POST or None, instance=emailmsg, initial={
'author': request.user, 'form': form_obj
Expand Down Expand Up @@ -247,7 +251,7 @@ def change_state(request, city):
event = get_event(city, request.user.is_authenticated, False)

if not state or not applications:
return JsonResponse({'error': 'Missing parameters'})
return JsonResponse({'error': _('Missing parameters')})

# cleanup applications so we don't put something unwated in the db
applications = [value for value in applications if value.isdigit()]
Expand All @@ -261,7 +265,7 @@ def change_state(request, city):
ids = [str(_id) for _id in ids]

return JsonResponse({
'message': 'Applications have been updated',
'message': _('Applications have been updated'),
'updated': ids
})

Expand All @@ -278,7 +282,7 @@ def change_rsvp(request, city):
event = get_event(city, request.user.is_authenticated, False)

if not rsvp_status or not applications:
return JsonResponse({'error': 'Missing parameters'})
return JsonResponse({'error': _('Missing parameters')})

applications = Application.objects.filter(
id__in=applications, form__event=event
Expand All @@ -289,7 +293,7 @@ def change_rsvp(request, city):
ids = [str(_id) for _id in ids]

return JsonResponse({
'message': 'Applications have been updated',
'message': _('Applications have been updated'),
'updated': ids
})

Expand All @@ -306,27 +310,29 @@ def rsvp(request, city, code):

application, rsvp = Application.get_by_rsvp_code(code, event)
if not application:
return redirect('/{}/'.format(event.page_url))
return redirect(f'/{event.page_url}/')

if application.rsvp_status != Application.RSVP_WAITING:
messages.error(
request,
"Something went wrong with your RSVP link. Please contact us at "
"{} with your name.".format(event.email)
_(
"Something went wrong with your RSVP link. Please contact us at "
"%(email)s with your name."
) % {'email': event.email}
)
return redirect('/{}/'.format(event.page_url))
return redirect(f'/{event.page_url}/')

application.rsvp_status = rsvp
application.save()

if rsvp == Application.RSVP_YES:
message = (
message = _(
"Your participation in the workshop has been confirmed! "
"We can't wait to meet you. We will be in "
"touch with details soon."
)
else:
message = (
message = _(
"Your answer has been saved, thanks for letting us know. Your "
"spot will be assigned to another person on the waiting list."
)
Expand Down
1 change: 0 additions & 1 deletion coach/__init__.py
@@ -1 +0,0 @@
default_app_config = 'coach.apps.CoachConfig'