diff --git a/CodeReview/settings.py b/CodeReview/settings.py index 1624c22..98b52cf 100644 --- a/CodeReview/settings.py +++ b/CodeReview/settings.py @@ -5,7 +5,6 @@ import os from pathlib import Path -# This option defines what folder is the root of the project BASE_DIR = Path(__file__).resolve().parent.parent # This option isn't part of the django framework, but it defines what stage of development we're in @@ -15,7 +14,6 @@ BASE_DIR = Path(__file__).resolve().parent.parent # Prod: We're in production and actively serving the site STAGE = os.getenv("DEV_STAGE", "Dev") -# This option defines if we're debugging, it's used to determine many aspects of the project DEBUG = STAGE != "Prod" # This option is used in encryption, if we're debugging, we don't care that people know what it is @@ -26,7 +24,6 @@ SECRET_KEY = 'django-insecure-1&=3d#^^j*!8)r5y8tuh(t#rp6*(jwbx%90k-ir5c*2j4$s$o% # But, in production we want to only let a specific url be used, so we load it from the environment ALLOWED_HOSTS = ['*'] if DEBUG else [os.getenv("PRODUCTION_HOST")] -# This option defines what apps to load INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', @@ -41,7 +38,6 @@ INSTALLED_APPS = [ 'Instructor', ] -# This option defines what middleware is run on a request, middleware is run before any view logic is executed MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', @@ -53,10 +49,8 @@ MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -# This option defines what urls.py file to use for urls ROOT_URLCONF = 'CodeReview.urls' -# This option defines how templates are rendered TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', @@ -78,7 +72,6 @@ TEMPLATES = [ # This option defines what wsgi application to use in development when running the app through runserver WSGI_APPLICATION = 'CodeReview.wsgi.application' -# This next block of code defines how our database will work and what database system will work if STAGE == "Prod": # In production, we use MySQL as our database backend DATABASES = { @@ -112,7 +105,6 @@ else: } } -# This option defines what backends we use for authentication if DEBUG: # If we're in development, we add django's model backend so that way we can debug AUTHENTICATION_BACKENDS = [ @@ -125,28 +117,20 @@ else: 'Users.ldap_auth.LDAPAuthentication', ] -# This option defines what Model to use in Auth backend for storing user data AUTH_USER_MODEL = "Users.User" -# This option defines what url to go when the user is not logged in LOGIN_URL = "/users/login" -# This option defines what url to go to after the user has logged in LOGIN_REDIRECT_URL = "/" -# This option defines what url to go to after logging out LOGOUT_REDIRECT_URL = "/users/logout-done" # LDAP AUTH -# This setting denotes what url to use to access the LDAP server LDAP_URL = os.getenv('LDAP_URL', "localhost") -# This setting tells ldap what NetBIOS domain name to use when logging in a user LDAP_DOMAIN = os.getenv('LDAP_DOMAIN', None) -# This setting tells ldap what base search context to use when searching for a user LDAP_BASE_CONTEXT = os.getenv('LDAP_BASE_CONTEXT', None) -# This next block of code defines how emails will work if DEBUG: # If we're debugging, we never actually send any emails, we just save what they would be as text files EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' @@ -166,10 +150,8 @@ else: SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -# This option defines what language code django will send to browsers LANGUAGE_CODE = 'en-us' -# This option defines what timezone the server is in TIME_ZONE = 'EST' # These options relate to localization, but, since this is an intranet site we don't need it. @@ -177,11 +159,9 @@ USE_I18N = False USE_L10N = False USE_TZ = False -# These options define urls and folders for static files STATIC_URL = '/static/' STATIC_ROOT = os.getenv("STATIC_DIR", "collected-static") -# This option defines which field to use automatically for PrimaryKeys DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' if DEBUG is False: @@ -203,7 +183,6 @@ if DEBUG is False: } if STAGE == "Prod" and os.getenv("SECURITY", "NONE") == "SECURE": - # We're running with HTTPS, enable some security features SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_PRELOAD = True @@ -211,9 +190,7 @@ if STAGE == "Prod" and os.getenv("SECURITY", "NONE") == "SECURE": SECURE_HSTS_SECONDS = 604800 SECURE_SSL_REDIRECT = True -# This next block of code initializes django-debug-toolbar if we're debugging if DEBUG: - # This option defines which IPs the toolbar will display on INTERNAL_IPS = [ '127.0.0.1' ] diff --git a/Main/context_processors.py b/Main/context_processors.py index de92750..ef5c291 100644 --- a/Main/context_processors.py +++ b/Main/context_processors.py @@ -8,7 +8,7 @@ from django.http import HttpRequest from Users.models import User -def base_context(request: HttpRequest) -> dict: +def base_context(request: HttpRequest) -> dict[str, object]: """ This context processor gives some basic info to templates. 'debug' tells the template if we're debugging right now. diff --git a/Main/forms.py b/Main/forms.py index d945082..a3bbda2 100644 --- a/Main/forms.py +++ b/Main/forms.py @@ -38,7 +38,7 @@ class GradeReviewWidget(TextInput): css = {'all': ('css/rubrics/rubric_table.css',)} js = ('js/rubrics/rubric-grade-widget.js',) - def get_context(self, name, value, attrs): + def get_context(self, name, value, attrs) -> dict[str, object]: """ This function defines context to pass when rendering this widget @@ -81,7 +81,7 @@ class ReviewForm(ModelForm): model = models.Review fields = ['schoology_id', 'rubric'] - def clean(self): + def clean(self) -> None: """ This function is run to validate form data. It ensures that a student can only have two requested reviews at once. @@ -106,7 +106,7 @@ class ReviewForm(ModelForm): else: self.add_error('schoology_id', self.SCHOOLOGY_ID_ERROR_MESSAGE) - def save(self, commit=True): + def save(self, commit=True) -> models.Review: """ This function is run to save the new Review It sets the review's student to the user that submitted the form @@ -181,7 +181,7 @@ class GradeReviewForm(ModelForm): 'additional_comments': Textarea(attrs={"style": "height: 150px;"}) } - def save(self, commit=True): + def save(self, commit=True) -> models.Review: """ This function runs when the Form is saving It reads the scores from JSON and makes ScoredRow objects @@ -206,7 +206,7 @@ class GradeReviewForm(ModelForm): field_order = ['scores', 'additional_comments'] - def clean(self): + def clean(self) -> None: """ This function is used to validate input data. It ensures the JSON submitted for scores is valid and readable. @@ -224,5 +224,3 @@ class GradeReviewForm(ModelForm): [self.add_error('scores', f"{error.message}") for error in errors] except JSONDecodeError: self.add_error('scores', "Invalid JSON") - - return self.cleaned_data diff --git a/Main/models.py b/Main/models.py index 3f355fa..02b7564 100644 --- a/Main/models.py +++ b/Main/models.py @@ -106,7 +106,7 @@ class Review(BaseModel): ordering = ['-date_completed', '-date_created'] - def __str__(self): + def __str__(self) -> str: """ This function defines how the model will be cast to a string @@ -116,7 +116,7 @@ class Review(BaseModel): return f"Review from {str(self.student)}" - def score_fraction(self): + def score_fraction(self) -> Optional[str]: """ This function returns the score a student got as a fraction. It will only run if the Review is closed @@ -133,7 +133,7 @@ class Review(BaseModel): return None @staticmethod - def get_status_from_string(status): + def get_status_from_string(status) -> str: """ This function gets the label for a status based off it's key ("O" would become "Open") diff --git a/Main/views.py b/Main/views.py index bf2eaa1..a85748a 100644 --- a/Main/views.py +++ b/Main/views.py @@ -67,7 +67,7 @@ class IsSuperUserMixin(UserPassesTestMixin): request = None - def test_func(self): + def test_func(self) -> bool: """ This is the function run to test the user @@ -85,7 +85,7 @@ class IsReviewerMixin(UserPassesTestMixin): request = None - def test_func(self): + def test_func(self) -> bool: """ This is the function run to test the user @@ -105,7 +105,7 @@ class FormNameMixin(ContextMixin): form_name = "Form" - def get_context_data(self, **kwargs): + def get_context_data(self, **kwargs) -> dict[str, object]: """ This function is run to get additional context data to pass to the template @@ -131,7 +131,7 @@ class FormAlertMixin(FormMixin): success_message: str = "Complete" failure_message: str = "The information you provided was incorrect, please correct the errors described below" - def form_valid(self, form): + def form_valid(self, form) -> HttpResponse: """ This function is run when the form is valid. It adds the success message to the messages framework @@ -143,7 +143,7 @@ class FormAlertMixin(FormMixin): messages.add_message(self.request, messages.SUCCESS, self.success_message) return super(FormAlertMixin, self).form_valid(form) - def form_invalid(self, form: Form): + def form_invalid(self, form: Form) -> HttpResponse: """ This function is run when the form is invalid. It adds the failure message to the messages framework @@ -169,7 +169,7 @@ class SuccessDeleteMixin(DeletionMixin): success_message: str = "Deleted" request = None - def form_valid(self, form): + def form_valid(self, form) -> HttpResponse: """ This function is run when the deletion has been confirmed by the user. It adds the success message to the messages framework. @@ -191,7 +191,7 @@ class HomeView(LoginRequiredMixin, TemplateView): template_name = "home.html" - def get(self, *args, **kwargs): + def get(self, *args, **kwargs) -> HttpResponse: """ This function is run when the user makes a GET request. It redirects the user to the instructor homepage if they're an instructor. @@ -205,7 +205,7 @@ class HomeView(LoginRequiredMixin, TemplateView): else: return super(HomeView, self).get(*args, **kwargs) - def get_context_data(self, **kwargs) -> dict: + def get_context_data(self, **kwargs) -> dict[str, object]: """ This function gives additional context data to the template. It gives a list of Reviews related to the user. @@ -252,7 +252,7 @@ class ReviewCreateView(LoginRequiredMixin, FormNameMixin, FormAlertMixin, Create form_name = "Create a Review" success_message = "New Review Saved" - def get_context_data(self, **kwargs): + def get_context_data(self, **kwargs) -> dict[str, object]: """ This function defines additional context data to pass to the template """ @@ -261,7 +261,7 @@ class ReviewCreateView(LoginRequiredMixin, FormNameMixin, FormAlertMixin, Create context['render_no_floating'] = True return context - def get_form_kwargs(self): + def get_form_kwargs(self) -> dict[str, object]: """ This function defines additional kwargs to pass to the form's constructor We give the user object so the Form can save the Review correctly @@ -274,7 +274,7 @@ class ReviewCreateView(LoginRequiredMixin, FormNameMixin, FormAlertMixin, Create kwargs['user'] = self.request.user return kwargs - def form_valid(self, form): + def form_valid(self, form) -> HttpResponse: """ This function is run when the form has been submitted and is valid It sends an email to all Reviewers telling them about the new Review @@ -309,7 +309,7 @@ class ReviewEditView(LoginRequiredMixin, FormNameMixin, FormAlertMixin, UpdateVi form_name = "Edit Review" success_message = "Review Updated" - def get_queryset(self): + def get_queryset(self) -> QuerySet: """ This function defines which Reviews a user can edit It only lets you edit a review in which you are the student, and it's not graded @@ -337,7 +337,7 @@ class ReviewCancelView(LoginRequiredMixin, SuccessDeleteMixin, DeleteView): model = models.Review success_message = "Review Cancelled" - def get_context_data(self, **kwargs) -> dict: + def get_context_data(self, **kwargs) -> dict[str, object]: """ This function provides additional context data to the template @@ -349,7 +349,7 @@ class ReviewCancelView(LoginRequiredMixin, SuccessDeleteMixin, DeleteView): context['objectString'] = f"review with schoology id: {self.object.schoology_id}" return context - def get_queryset(self): + def get_queryset(self) -> QuerySey: """ This function defines what Reviews the user can cancel It limits it to the Reviews where the user is the student and Reviews that aren't closed @@ -377,7 +377,7 @@ class ReviewDeleteView(LoginRequiredMixin, IsSuperUserMixin, SuccessDeleteMixin, model = models.Review success_message = "Review Deleted" - def get_context_data(self, **kwargs): + def get_context_data(self, **kwargs) -> dict[str, object]: """ This function provides additional context data to the template @@ -400,7 +400,7 @@ class ReviewClaimView(LoginRequiredMixin, IsReviewerMixin, View): http_method_names = ['post'] - def post(self, request, *args, **kwargs): + def post(self, request, *args, **kwargs) -> HttpResponse: """ This function defines what will happen on a POST request @@ -508,7 +508,7 @@ class ReviewGradeView(LoginRequiredMixin, IsReviewerMixin, FormNameMixin, FormAl form_name = "Grade Review" success_message = "Review Graded" - def get_queryset(self): + def get_queryset(self) -> QuerySet: """ This function defines what Reviews can be graded It restricts it to Reviews that are assigned and reviews where the user is the reviewer @@ -519,7 +519,7 @@ class ReviewGradeView(LoginRequiredMixin, IsReviewerMixin, FormNameMixin, FormAl return models.Review.objects.filter(reviewer=self.request.user, status=models.Review.Status.ASSIGNED) - def form_valid(self, form): + def form_valid(self, form) -> HttpResponse: """ This function is run if the form is valid It saves the date and time the Review was graded and sends an email to the instructor @@ -551,7 +551,7 @@ class ReviewDetailView(LoginRequiredMixin, DetailView): model = models.Review context_object_name = 'review' - def get_queryset(self): + def get_queryset(self) -> QuerySet: """ This function restricts what Reviews the user can view If they're an admin, they cna view any completed reviews @@ -562,7 +562,7 @@ class ReviewDetailView(LoginRequiredMixin, DetailView): """ query = models.Review.objects.filter(status=models.Review.Status.CLOSED) - if not self.request.user.is_superuser: + if self.request.user.is_superuser is False: query = query.filter(Q(student=self.request.user) | Q(reviewer=self.request.user)) return query @@ -582,7 +582,7 @@ class ReviewCompleteListView(LoginRequiredMixin, ListView): paginate_by = 10 context_object_name = 'reviews' - def get_session(self): + def get_session(self) -> Optional[str]: """ This function gets the session the instructor requested @@ -596,7 +596,7 @@ class ReviewCompleteListView(LoginRequiredMixin, ListView): else: return None - def get_context_data(self, *, object_list=None, **kwargs): + def get_context_data(self, *, object_list=None, **kwargs) -> dict[str, object]: """ This function provides additional context data to the template @@ -610,7 +610,7 @@ class ReviewCompleteListView(LoginRequiredMixin, ListView): context['opposite_session'] = "PM" if self.get_session() == "AM" else "AM" return context - def get_queryset(self): + def get_queryset(self) -> QuerySet: """ This function limits which Reviews are listed If the user is an instructor, it shows all completed reviews @@ -643,7 +643,7 @@ class BaseErrorView(TemplateView): http_method_names = ['get', 'post'] - def post(self, request, *args, **kwargs): + def post(self, request, *args, **kwargs) -> HttpResponse: return render(request, self.template_name, self.get_context_data()) @@ -686,7 +686,7 @@ class Error(View): http_method_names = ['get', 'post'] - def get(self, request, *args, **kwargs): + def get(self, request, *args, **kwargs) -> HttpResponse: """ This function is run when a GET request is received It gets the requested error page, defaulting to 404 @@ -698,7 +698,7 @@ class Error(View): else: return self.error_dict.get(error_type, Error404).as_view()(request, *args, **kwargs) - def post(self, request, *args, **kwargs): + def post(self, request, *args, **kwargs) -> HttpResponse: """ This function is run when the view receives a POST request It returns an error page @@ -713,7 +713,7 @@ error_404_handler = Error404.as_view() error_403_handler = Error403.as_view() -def error_500_handler(request): +def error_500_handler(request) -> HttpResponse: """ This function is run in the event of a 500 error """