Skip to content

Commit

Permalink
updated per django
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonLovesDoggo committed Jan 3, 2024
1 parent 4ab0fdf commit 8042bc9
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 67 deletions.
4 changes: 2 additions & 2 deletions core/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -621,13 +621,13 @@ class UserAdmin(admin.ModelAdmin):
actions = [send_test_notif, send_notif_singleday, reset_password]
action_form = AdminPasswordResetForm # admin reset password form
form = UserAdminForm

def get_inline_instances(self, request, obj=None):
if obj and StaffMember.objects.filter(user=obj).exists():
# Add StaffMemberInline if the user has a related StaffMember
return [StaffMemberInline(self.model, self.admin_site)]
return []

def has_view_permission(self, request, obj=None):
if obj is None and (
request.user.organizations_owning.exists()
Expand Down
5 changes: 3 additions & 2 deletions core/api/views/staff.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
from core.api.serializers.custom import SingleUserField
from core.models import StaffMember


class StaffSerializer(serializers.ModelSerializer):
user = SingleUserField()
bio = serializers.CharField()
is_alumni = serializers.ReadOnlyField()



class Meta:
model = StaffMember
fields = ["user", "bio", "positions", "positions_leading", "years", "is_alumni"]


@api_view(["GET"])
def staff(request, year=None):
"""
Expand Down
9 changes: 4 additions & 5 deletions core/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,19 +121,19 @@ class StaffMember(models.Model):

def __str__(self):
return f"{self.user.get_full_name()} ({self.user})"

@property
def is_alumni(self):
current_year = timezone.now().year
current_month = timezone.now().month

# If the current month is between January and July, use the previous year
if 1 <= current_month <= 7:
current_year -= 1

current_year_range = f"{current_year}-{str(current_year + 1)[-2:]}"
return current_year_range not in self.years

class Meta:
verbose_name = "Staff Member"
verbose_name_plural = "Staff Members"
Expand All @@ -143,4 +143,3 @@ class Meta:
name="unique_staff_member",
)
]

42 changes: 28 additions & 14 deletions core/utils/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,10 @@ def _get_val_from_obj(self, obj):

from django import forms
from django.conf import settings
from django.contrib.postgres.fields import (JSONField as DjangoJSONField, ArrayField as DjangoArrayField, )
from django.db.models import JSONField as DjangoJSONField
from django.contrib.postgres.fields import (
ArrayField as DjangoArrayField,
)
from django.db.models import Field


Expand All @@ -170,56 +173,67 @@ class JSONField(DjangoJSONField):

class ArrayField(DjangoArrayField):
def formfield(self, **kwargs):
defaults = {'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, }
defaults = {
"form_class": forms.MultipleChoiceField,
"choices": self.base_field.choices,
}
defaults.update(kwargs)
# Skip our parent's formfield implementation completely as we don't
# care for it.
# pylint:disable=bad-super-call
return super(ArrayField, self).formfield(**defaults)


if 'sqlite' in settings.DATABASES['default']['ENGINE']:
if "sqlite" in settings.DATABASES["default"]["ENGINE"]:

class JSONField(Field):
def db_type(self, connection):
return 'text'
return "text"

def from_db_value(self, value, expression, connection):
if value is not None:
return self.to_python(value)
return value

def to_python(self, value):
if value is not None:
try:
return json.loads(value)
except (TypeError, ValueError):
return value
return value

def get_prep_value(self, value):
if value is not None:
return str(json.dumps(value))
return value

def value_to_string(self, obj):
return self.value_from_object(obj)



class ArrayField(JSONField):
def __init__(self, base_field, size=None, **kwargs):
"""Care for DjangoArrayField's kwargs."""
self.base_field = base_field
self.size = size
super().__init__(**kwargs)

def deconstruct(self):
"""Need to create migrations properly."""
name, path, args, kwargs = super().deconstruct()
kwargs.update({'base_field': self.base_field.clone(), 'size': self.size, })
kwargs.update(
{
"base_field": self.base_field.clone(),
"size": self.size,
}
)
return name, path, args, kwargs

def formfield(self, **kwargs):
defaults = {'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, }
defaults = {
"form_class": forms.MultipleChoiceField,
"choices": self.base_field.choices,
}
defaults.update(kwargs)
# Skip our parent's formfield implementation completely as we don't
# care for it.
Expand Down
4 changes: 3 additions & 1 deletion core/utils/local_date.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ def get_localdate(date=None, time=None):

def generate_years():
current_year = timezone.now().year
year_ranges = [f"{year}-{str(year + 1)[-2:]}" for year in range(2021, current_year + 2)]
year_ranges = [
f"{year}-{str(year + 1)[-2:]}" for year in range(2021, current_year + 2)
]
years = zip(year_ranges, year_ranges)
return list(years)
58 changes: 31 additions & 27 deletions core/views/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
class Index(TemplateView, mixins.TitleMixin):
template_name = "core/index.html"
title = "Home"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)

context["announcements"] = models.Announcement.get_all(user=self.request.user)[
:3
]
:3
]

datetime_now = timezone.localtime()
events1 = (
lambda: models.Event.get_events(user=self.request.user)
Expand All @@ -46,9 +46,9 @@ def get_context_data(self, **kwargs):
Q(schedule_format="default"),
)[: 3 - len(events)]
context["events"] = events

context["blogpost"] = models.BlogPost.public().first()

context["banner_data"] = get_week_schedule_info(self.request.user)
return context

Expand All @@ -62,66 +62,66 @@ class CalendarFeed(ICalFeed, View):
product_id = "-//maclyonsden.com//calendar//EN"
timezone = "UTC"
file_name = "metropolis_school-wide.ics"

def items(self):
now = timezone.now()
padding = settings.ICAL_PADDING
return (
models.Event.get_events(user=None)
.filter(
end_date__gte=now
- padding, # todo add ?start= and ?end= to url via self.request.query_params
- padding, # todo add ?start= and ?end= to url via self.request.query_params
start_date__lte=now + padding,
)
.order_by("-start_date")
)

def item_title(self, item):
return item.name

def item_description(self, item):
return item.description

def _is_hms(self, dt, hour, minute, second):
return dt.hour == hour and dt.minute == minute and dt.second == second

def item_rrule(self, item: models.Event):
if hasattr(item, "reoccurrences") and item.reoccurrences.rule:
return item.reoccurrences.rule
return None

def item_start_datetime(self, item):
return (
item.start_date
if self._is_hms(item.start_date, 0, 0, 0)
else item.start_date.date()
)

def item_end_datetime(self, item):
return (
item.end_date
if self._is_hms(item.end_date, 23, 59, 0)
else item.end_date.date()
)

def item_link(self, item):
return reverse("calendar") + f"?pk={item.pk}" # NOTE: workaround for UID

def item_categories(self, item):
return (
[tag.name for tag in item.tags.all()]
+ (["public"] if item.is_public else [])
+ (["instructional"] if item.is_instructional else [])
[tag.name for tag in item.tags.all()]
+ (["public"] if item.is_public else [])
+ (["instructional"] if item.is_instructional else [])
)

def item_author_name(self, item):
return item.organization.name


class MapView(TemplateView, mixins.TitleMixin):
template_name = "core/map/map.html"
title = "Map"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["mapbox_apikey"] = {"apikey": settings.MAPBOX_APIKEY}
Expand All @@ -131,27 +131,28 @@ def get_context_data(self, **kwargs):
class AboutView(TemplateView, mixins.TitleMixin):
template_name = "core/about/about.html"
title = "About"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
members_data = StaffSerializer(StaffMember.objects.all(), many=True).data

# Group members based on positions and alumni status
grouped_members = sorteddict(Alumni=[])
for member in members_data:
positions = member.get("positions", [])
if member["is_alumni"]:
grouped_members["Alumni"].append(member)
continue

for position in positions:
if position not in grouped_members:
grouped_members[position] = []
grouped_members[position].append(member)

context["members"] = dict(grouped_members)
context["member_count"] = len(members_data)
import json

print(json.dumps(context["members"], indent=4))
return context

Expand All @@ -173,4 +174,7 @@ def get(self, request):
class Json(View):
@staticmethod
def get(request):
return Response({"message": "hi", "name": "NOT JSON DERULO"}, status=418, )
return Response(
{"message": "hi", "name": "NOT JSON DERULO"},
status=418,
)
4 changes: 1 addition & 3 deletions metropolis/docker_settings.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from pathlib import Path


_using_docker_config = True # intended for allow changing config *in dev*

BASE_DIR = Path(__file__).resolve().parent.parent
Expand All @@ -25,10 +24,9 @@
},
}


DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"ENGINE": "django.db.backends.postgresql",
"NAME": "metropolis_db",
"USER": "metropolis_user",
"PASSWORD": "changeme_metropolis_password", # overwritten by local settings
Expand Down
44 changes: 31 additions & 13 deletions static/css/materialize.min.css

Large diffs are not rendered by default.

0 comments on commit 8042bc9

Please sign in to comment.