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

Faster Way To Add Late Starts #285

Merged
merged 5 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion core/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
TermAdminForm,
UserAdminForm,
UserCreationAdminForm,
LateStartEventForm
)
from .models import Comment, StaffMember
from .utils.actions import (
Expand All @@ -48,6 +49,11 @@
PostTypeFilter,
)

from django.template.response import TemplateResponse
from django.shortcuts import redirect
from django.urls import path
from datetime import datetime, time

User = get_user_model()

# Register your models here.
Expand Down Expand Up @@ -546,13 +552,59 @@ def formfield_for_manytomany(self, db_field, request, **kwargs):
kwargs["queryset"] = models.Tag.objects.all().order_by("name")
return super().formfield_for_manytomany(db_field, request, **kwargs)


class EventAdmin(CustomTimeMixin, admin.ModelAdmin):
list_display = ["name", "organization", "start_date", "end_date"]
list_filter = [OrganizationListFilter]
ordering = ["-start_date", "-end_date"]
search_fields = ["name"]

def get_urls(self):
return [
path(
"createLateStart/",
self.admin_site.admin_view(self.late_start_view)
),
*super().get_urls(),
]

def late_start_view(self, request):

url = request.get_full_path()

context = dict(
self.admin_site.each_context(request),
form=LateStartEventForm,
url=url,
title='Add Late Start',
media=LateStartEventForm().media
)

if request.method == 'POST':
form = LateStartEventForm(request.POST)
if form.is_valid():
start_date_value = form.cleaned_data.get('start_date')
start_date = datetime.combine(start_date_value, time(hour=10))
end_date = datetime.combine(start_date_value, time(hour=10, second=1))

organization = form.cleaned_data.get('organization')

data = {
'name': 'Late Start',
'term': models.Term.get_current(start_date),
'organization': organization,
'schedule_format': 'late-start',
'start_date': start_date,
'end_date': end_date
}

models.Event.objects.create(**data)
return redirect("/admin/core/event")
else:
context['form'] = form
return TemplateResponse(request, "admin/custom_form.html", context)
else:
return TemplateResponse(request, "admin/custom_form.html", context)

def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
Expand Down
25 changes: 25 additions & 0 deletions core/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.contrib.auth.forms import (
AdminUserCreationForm as ContribAdminUserCreationForm,
)
from django.contrib.admin.widgets import AdminDateWidget
from django.utils import timezone
from django_select2 import forms as s2forms
from martor.widgets import AdminMartorWidget
Expand All @@ -13,6 +14,7 @@
from core.views.mixins import CaseInsensitiveUsernameMixin



class MetropolisSignupForm(SignupForm, CaseInsensitiveUsernameMixin):
first_name = forms.CharField(
max_length=30,
Expand Down Expand Up @@ -295,3 +297,26 @@ class UserAdminForm(CaseInsensitiveUsernameMixin, ContribUserChangeForm):

class UserCreationAdminForm(CaseInsensitiveUsernameMixin, ContribAdminUserCreationForm):
pass

class LateStartEventForm(forms.Form):
start_date = forms.DateField(widget=AdminDateWidget())
organization = forms.ModelChoiceField(
queryset=models.Organization.objects.all(),
required=True
)

def __init__(self, *args, **kwargs):
super(LateStartEventForm, self).__init__(*args, **kwargs)

try:
self.fields["organization"].initial = models.Organization.objects.get(name='SAC')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be querying organizations by pk instead of name

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eh, this way is honestly more adaptable as not all db instance will have the same SAC PK... but on this it should be the "School" org

see #285 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean the "school" organization? Is that not just SAC? Also, for creating a school if it doesn't exist, would you just make the owner and execs just the admin currently using the form?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, there is a school org that is behind something like a late start or an admin related presentation.

As for the user, just pick the first created superuser (filter by date created and is_superuser).first()

except models.Organization.DoesNotExist:
pass


def clean(self):
cleaned_data = super().clean()
if cleaned_data.get('start_date') != None and models.Term.get_current(cleaned_data['start_date']) == None:
raise forms.ValidationError(
{'start_date': 'No Term Found For Date'}
)
2 changes: 1 addition & 1 deletion core/models/course.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def get_events(cls, user=None):
return events

def clean(self):
if self.start_date > self.end_date:
if self.start_date != None and self.end_date != None and self.start_date > self.end_date:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reason for changing this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was mildly annoying me when testing some things. This change can 100% be dropped.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well there should never be an event without a start/end date set. that is enforced both on the model both by the super().clean() and on the database level.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it shouldn't. Honestly, I don't remember exactly why I added that. However, I do know for a fact that if you fill out the event add form and set either one of the dates to be an invalid one, when you submit it would give you a TypeError due to comparing NoneType and a datetime.datetime. That's probably why I added that when I was testing some things, but I should probably just remove this change.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's up for handling in the form's logic though, not model's

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea but I was just looking where the error happened and changed that. I'll just remove this change then.

raise ValidationError(
{
"start_date": _("Start date must be before end date"),
Expand Down
49 changes: 49 additions & 0 deletions templates/admin/custom_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}

{% block extrahead %}
{{ block.super }}
<script src="{% url 'admin:jsi18n' %}"></script>
<script src="{% static "admin/js/core.js" %}"></script>
{{ media }}
{% endblock %}

{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}">
{% endblock %}

{% if not is_popup %}
{% block breadcrumbs %}<div class="breadcrumbs" style="height:0px;padding:0px"></div>{% endblock %}
{% endif %}

{% block coltype %}colM{% endblock %}
{% block content %}
<form action="{{ url }}" method="post">
{% csrf_token %}
{% if form.errors %}
<p class="errornote">
{% if form.errors|length == 1 %}
{% translate "Please correct the error below." %}
{% else %}
{% translate "Please correct the errors below." %}
{% endif %}
</p>
{% endif %}
<fieldset class="module aligned ">
{% for field in form %}
<div class="form-row field-name">
{{ field.errors }}
<div>
<div class="flex-container">
{{ field.label_tag }} {{ field }}
</div>
</div>
</div>
{% endfor %}
</fieldset>
<div class="submit-row">
<input class="default" type="submit" value="Save">
</div>
</form>
{% endblock %}
Loading