-
-
Notifications
You must be signed in to change notification settings - Fork 672
Expand file tree
/
Copy pathviews.py
More file actions
372 lines (279 loc) · 14.3 KB
/
views.py
File metadata and controls
372 lines (279 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""Views for user profiles, PSF membership, and sponsorship management."""
from collections import defaultdict
from allauth.account.views import PasswordChangeView, SignupView
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.mail import send_mail
from django.db.models import Subquery
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
from honeypot.decorators import check_honeypot
from apps.sponsors.forms import SponsorRequiredAssetsForm, SponsorUpdateForm
from apps.sponsors.models import BenefitFeature, Sponsor, Sponsorship
from apps.users.forms import MembershipForm, MembershipUpdateForm, UserProfileForm
from apps.users.models import Membership
from pydotorg.mixins import LoginRequiredMixin
User = get_user_model()
class MembershipCreate(LoginRequiredMixin, CreateView):
"""Create a new PSF Basic membership for the logged-in user."""
model = Membership
form_class = MembershipForm
template_name = "users/membership_form.html"
@method_decorator(check_honeypot)
def dispatch(self, *args, **kwargs):
"""Redirect to edit if user already has a membership."""
if self.request.user.is_authenticated and self.request.user.has_membership:
return redirect("users:user_membership_edit")
return super().dispatch(*args, **kwargs)
def get_form_kwargs(self):
"""Pre-fill the email address from the user's account."""
kwargs = super().get_form_kwargs()
kwargs["initial"] = {"email_address": self.request.user.email}
return kwargs
def form_valid(self, form):
"""Save membership linked to the current user and subscribe to mailing list."""
self.object = form.save(commit=False)
self.object.creator = self.request.user
self.object.save()
# Send subscription email to mailing lists
if settings.MAILING_LIST_PSF_MEMBERS and self.object.psf_announcements:
send_mail(
subject="PSF Members Announce Signup from python.org",
message="subscribe",
from_email=self.object.creator.email,
recipient_list=[settings.MAILING_LIST_PSF_MEMBERS],
)
return super().form_valid(form)
def get_success_url(self):
"""Redirect to the membership thanks page."""
return reverse("users:user_membership_thanks")
class MembershipUpdate(LoginRequiredMixin, UpdateView):
"""Update an existing PSF membership."""
form_class = MembershipUpdateForm
template_name = "users/membership_form.html"
@method_decorator(check_honeypot)
def dispatch(self, *args, **kwargs):
"""Apply honeypot check before dispatching."""
return super().dispatch(*args, **kwargs)
def get_object(self):
"""Return the current user's membership or raise 404."""
if self.request.user.has_membership:
return self.request.user.membership
raise Http404
def form_valid(self, form):
"""Save the membership with the current user as creator."""
self.object = form.save(commit=False)
self.object.creator = self.request.user
self.object.save()
return super().form_valid(form)
def get_success_url(self):
"""Redirect to the membership thanks page."""
return reverse("users:user_membership_thanks")
class MembershipThanks(TemplateView):
"""Display a thank-you page after membership creation or update."""
template_name = "users/membership_thanks.html"
class MembershipVoteAffirm(TemplateView):
"""Display and process the annual vote affirmation form."""
template_name = "users/membership_vote_affirm.html"
def post(self, request, *args, **kwargs):
"""Store the vote affirmation."""
self.request.user.membership.votes = True
self.request.user.membership.last_vote_affirmation = timezone.now()
self.request.user.membership.save()
return redirect("users:membership_affirm_vote_done")
class MembershipVoteAffirmDone(TemplateView):
"""Display confirmation after vote affirmation is complete."""
template_name = "users/membership_vote_affirm_done.html"
class UserUpdate(LoginRequiredMixin, UpdateView):
"""Edit the current user's profile information."""
form_class = UserProfileForm
slug_field = "username"
template_name = "users/user_form.html"
@method_decorator(check_honeypot)
def dispatch(self, *args, **kwargs):
"""Apply honeypot check before dispatching."""
return super().dispatch(*args, **kwargs)
def get_object(self, queryset=None):
"""Return the current logged-in user."""
return User.objects.get(username=self.request.user)
class UserDetail(DetailView):
"""Display a user's public profile page."""
slug_field = "username"
def get_queryset(self):
"""Return all users if viewing own profile, searchable users otherwise."""
queryset = User.objects.select_related()
if self.request.user.username == self.kwargs["slug"]:
return queryset
return queryset.searchable()
class HoneypotSignupView(SignupView):
"""Signup view with honeypot spam protection."""
@method_decorator(check_honeypot)
def dispatch(self, *args, **kwargs):
"""Apply honeypot check before dispatching."""
return super().dispatch(*args, **kwargs)
class CustomPasswordChangeView(LoginRequiredMixin, PasswordChangeView):
"""Password change view with honeypot protection and custom redirect."""
# Add honeypot support to 'password change' form and
# redirect it to the user editing form.
@method_decorator(check_honeypot)
def dispatch(self, *args, **kwargs):
"""Apply honeypot check before dispatching."""
return super().dispatch(*args, **kwargs)
def get_success_url(self):
"""Redirect to the user profile edit page after password change."""
return reverse("users:user_profile_edit")
class UserDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
"""Allow users to delete their own account."""
model = User
success_url = reverse_lazy("home")
slug_field = "username"
raise_exception = True
http_method_names = ["post", "delete"]
def test_func(self):
"""Only allow users to delete their own account."""
return self.get_object() == self.request.user
class MembershipDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
"""Allow users to delete their own PSF membership."""
model = Membership
slug_field = "creator__username"
raise_exception = True
http_method_names = ["post", "delete"]
def get_success_url(self):
"""Redirect to the user's profile page after deletion."""
return reverse("users:user_detail", kwargs={"slug": self.request.user.username})
def test_func(self):
"""Only allow the membership creator to delete it."""
return self.get_object().creator == self.request.user
class UserNominationsView(LoginRequiredMixin, TemplateView):
"""Display all nominations received and made by the current user."""
model = User
template_name = "users/nominations_view.html"
def get_queryset(self):
"""Return users with related objects."""
return User.objects.select_related()
def get_context_data(self, **kwargs):
"""Build grouped nominations by election for the current user."""
context = super().get_context_data(**kwargs)
elections = defaultdict(lambda: {"nominations_recieved": [], "nominations_made": []})
for nomination in self.request.user.nominations_recieved.all():
nominations = nomination.nominations.all()
for nomin in nominations:
nomin.is_editable = nomin.editable(user=self.request.user)
elections[nomination.election]["nominations_recieved"].append(nomin)
for nomination in self.request.user.nominations_made.all():
nomination.is_editable = nomination.editable(user=self.request.user)
elections[nomination.election]["nominations_made"].append(nomination)
context["elections"] = dict(sorted(dict(elections).items(), key=lambda item: item[0].date, reverse=True))
return context
@method_decorator(login_required(login_url=settings.LOGIN_URL), name="dispatch")
class UserSponsorshipsDashboard(ListView):
"""Dashboard listing all sponsorships associated with the current user."""
context_object_name = "sponsorships"
template_name = "users/list_user_sponsorships.html"
def get_queryset(self):
"""Return sponsorships visible to the current user."""
return self.request.user.sponsorships.select_related("sponsor")
def get_context_data(self, *args, **kwargs):
"""Split sponsorships into active and grouped-by-status inactive lists."""
context = super().get_context_data(*args, **kwargs)
sponsorships = context["sponsorships"]
context["active"] = [sp for sp in sponsorships if sp.is_active]
by_status = []
inactive = [sp for sp in sponsorships if not sp.is_active]
for value, label in Sponsorship.STATUS_CHOICES[::-1]:
by_status.append((label, [sp for sp in inactive if sp.status == value]))
context["by_status"] = by_status
return context
@method_decorator(login_required(login_url=settings.LOGIN_URL), name="dispatch")
class SponsorshipDetailView(DetailView):
"""Display detailed information about a specific sponsorship."""
context_object_name = "sponsorship"
template_name = "users/sponsorship_detail.html"
def get_queryset(self):
"""Return all sponsorships for superusers, user-visible ones otherwise."""
if self.request.user.is_superuser:
return Sponsorship.objects.select_related("sponsor").all()
return self.request.user.sponsorships.select_related("sponsor")
def get_context_data(self, *args, **kwargs):
"""Add required, fulfilled, and provided asset lists to the context."""
context = super().get_context_data(*args, **kwargs)
sponsorship = context["sponsorship"]
required_assets = BenefitFeature.objects.required_assets().from_sponsorship(sponsorship)
fulfilled, pending = [], []
for asset in required_assets:
if bool(asset.value):
fulfilled.append(asset)
else:
pending.append(asset)
provided_assets = BenefitFeature.objects.provided_assets().from_sponsorship(sponsorship)
provided = [asset for asset in provided_assets if bool(asset.value)]
context["required_assets"] = pending
context["fulfilled_assets"] = fulfilled
context["provided_assets"] = provided
context["sponsor"] = sponsorship.sponsor
return context
@method_decorator(login_required(login_url=settings.LOGIN_URL), name="dispatch")
class UpdateSponsorInfoView(UpdateView):
"""Edit sponsor organization information."""
object_name = "sponsor"
template_name = "sponsors/new_sponsorship_application_form.html"
form_class = SponsorUpdateForm
def get_queryset(self):
"""Return all sponsors for superusers, user-associated sponsors otherwise."""
if self.request.user.is_superuser:
return Sponsor.objects.all()
sponsor_ids = self.request.user.sponsorships.values_list("sponsor_id", flat=True)
return Sponsor.objects.filter(id__in=Subquery(sponsor_ids))
def get_success_url(self):
"""Display success message and redirect back to the edit form."""
messages.add_message(self.request, messages.SUCCESS, "Sponsor info updated with success.")
return self.request.path
@login_required(login_url=settings.LOGIN_URL)
def edit_sponsor_info_implicit(request):
"""Redirect to the sponsor edit page, handling zero or multiple sponsors."""
sponsors = Sponsor.objects.filter(contacts__user=request.user).all()
if len(sponsors) == 0:
messages.add_message(request, messages.INFO, "No Sponsors associated with your user.")
return redirect("users:user_profile_edit")
if len(sponsors) == 1:
return redirect("users:edit_sponsor_info", pk=sponsors[0].id)
messages.add_message(request, messages.INFO, "Multiple Sponsors associated with your user.")
return render(request, "users/sponsor_select.html", context={"sponsors": sponsors})
@method_decorator(login_required(login_url=settings.LOGIN_URL), name="dispatch")
class UpdateSponsorshipAssetsView(UpdateView):
"""Upload or update required sponsorship assets."""
object_name = "sponsorship"
template_name = "users/sponsorship_assets_update.html"
form_class = SponsorRequiredAssetsForm
def get_queryset(self):
"""Return all sponsorships for superusers, user-visible ones otherwise."""
if self.request.user.is_superuser:
return Sponsorship.objects.select_related("sponsor").all()
return self.request.user.sponsorships.select_related("sponsor")
def get_form_kwargs(self):
"""Add optional required_assets_ids filter from query parameters."""
kwargs = super().get_form_kwargs()
specific_asset = self.request.GET.get("required_asset", None)
if specific_asset:
kwargs["required_assets_ids"] = [specific_asset]
return kwargs
def get_context_data(self, **kwargs):
"""Add the required_asset_id from the query string to the context."""
context = super().get_context_data(**kwargs)
context["required_asset_id"] = self.request.GET.get("required_asset", None)
return context
def get_success_url(self):
"""Display success message and redirect to sponsorship detail."""
messages.add_message(self.request, messages.SUCCESS, "Assets were updated with success.")
return reverse("users:sponsorship_application_detail", args=[self.object.pk])
def form_valid(self, form):
"""Update assets and redirect to the success URL."""
form.update_assets()
return redirect(self.get_success_url())