def run(*args): """ Space seperated list with --script-args "path_to_file" "path2_to_file" :param args: List of files to read pledge forms :return: None python manage.py runscript load_pledge_forms --script-args secrets/20200205_pledgeforms.csv """ for path in args: with open(path) as f: reader = csv.DictReader(f) for pledge_form in reader: chapter_obj = Chapter.get_school_chapter( pledge_form["School Name"]) name = f'{pledge_form["Legal First Name"]} {pledge_form["Full Middle Name"]} {pledge_form["Last Name"]}' form_obj = Pledge( name=name, chapter=chapter_obj, email=pledge_form["School E-mail"], created=datetime.strptime(pledge_form["Submission Date"], "%Y-%m-%d %H:%M:%S"), ) try: with transaction.atomic(): form_obj.save() except IntegrityError: warnings.warn(f"{name} already existed for {chapter_obj}") continue
class AdvisorListFilter(django_filters.FilterSet): region = django_filters.ChoiceFilter(choices=Region.region_choices(), method="filter_region") chapter = django_filters.ChoiceFilter( label="Chapter", choices=Chapter.chapter_choices(), method="filter_chapter", ) class Meta: model = User fields = { "name": ["icontains"], "chapter": ["exact"], } order_by = ["name"] def filter_region(self, queryset, field_name, value): if value == "national": return queryset elif value == "candidate_chapter": queryset = queryset.filter(chapter__candidate_chapter=True) else: queryset = queryset.filter(chapter__region__slug=value) return queryset
class GearArticleListFilter(django_filters.FilterSet): region = django_filters.ChoiceFilter( label="Region", choices=Region.region_choices(), method="filter_region" ) chapter = django_filters.ChoiceFilter( label="Chapter", choices=Chapter.chapter_choices(), method="filter_chapter" ) date = DateRangeFilter(label="Submit Date") class Meta: fields = ["region", "chapter", "reviewed", "date"] model = GearArticle order_by = ["chapter"] def filter_region(self, queryset, field_name, value): if value == "national": return queryset elif value == "candidate_chapter": queryset = queryset.filter(chapter__candidate_chapter=True) else: queryset = queryset.filter(chapter__region__slug=value) return queryset def filter_chapter(self, queryset, field_name, value): if value: queryset = queryset.filter(submission__chapter__slug=value) return queryset
def create_chapter(self, number, introduction=None): """Create Chapter object. Args: number: Identifier of the chapter (int). Returns: Chapter object. """ if not introduction: introduction = "<p>Introduction for chapter {}</p>".format(number) chapter = Chapter( slug="chapter-{}".format(number), name="Chapter {}".format(number), number=number, introduction=introduction, ) chapter.save() return chapter
class UserAlterForm(forms.ModelForm): role = forms.ChoiceField(choices=UserAlter.ROLES, required=False) chapter = forms.ChoiceField(choices=Chapter.chapter_choices(), required=True) class Meta: model = UserAlter fields = ["chapter", "role"] def clean_chapter(self): data = self.cleaned_data["chapter"] chapter = Chapter.objects.filter(slug=data).first() return chapter
def create(request, id): data = {} subject = Subject.objects.get(pk=id) chapter = Chapter() chapter.chapter_title = request.POST.get('chapter_title') chapter.chapter_name = request.POST.get('chapter_name') chapter.subject = subject chapter.save() data['chapter'] = serializers.serialize( 'json', Chapter.objects.filter(pk=chapter.id)) return JsonResponse(data)
def create_superuser(self, email, password, **extra_fields): chapter = Chapter.objects.first() if chapter is None: # this would happen on first install; make a default test region/chapter from regions.models import Region region = Region.objects.first() if region is None: Region(name="Test Region").save() region = Region.objects.first() Chapter(name="Test Chapter", region=region).save() chapter = Chapter.objects.first() extra_fields.setdefault("chapter", chapter) super().create_superuser(email=email, password=password, **extra_fields)
def __init__(self, *args, **kwargs): natoff = kwargs.get("natoff", False) if natoff: kwargs.pop("natoff") self.base_filters["region"] = django_filters.ChoiceFilter( choices=Region.region_choices(), method="filter_region" ) self.base_filters["chapter"] = django_filters.ChoiceFilter( label="Chapter", choices=Chapter.chapter_choices(), method="filter_chapter", ) self.base_filters["pictures"] = django_filters.ChoiceFilter( label="Pictures", choices=((True, "1+"), (False, "None")), method="filter_pictures", ) super().__init__(*args, **kwargs)
class AuditListFilter(django_filters.FilterSet): modified = DateRangeFilter() chapter = django_filters.ChoiceFilter( label="Chapter", choices=Chapter.chapter_choices(), method="filter_chapter", ) class Meta: model = Audit fields = [ "modified", "chapter", "user__chapter__region", "debit_card", ] order_by = ["user__chapter"] def filter_chapter(self, queryset, field_name, value): if value: queryset = queryset.filter(user__chapter__slug=value) return queryset
class UserRoleListFilter(django_filters.FilterSet): current_status = django_filters.ChoiceFilter( choices=[ ("active", "active"), ("pnm", "prospective"), ], method="filter_current_status", ) role = django_filters.MultipleChoiceFilter(choices=UserRoleChange.ROLES, method="filter_role") region = django_filters.ChoiceFilter(choices=Region.region_choices(), method="filter_region") major = django_filters.ModelChoiceFilter( queryset=ChapterCurricula.objects.none(), method="filter_major", ) chapter = django_filters.ChoiceFilter( label="Chapter", choices=Chapter.chapter_choices(), method="filter_chapter", ) class Meta: model = User fields = { "name": ["icontains"], "major": ["exact"], "graduation_year": ["icontains"], "chapter": ["exact"], } order_by = ["name"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters["major"].queryset = ChapterCurricula.objects.values_list( "major", flat=True, ).distinct() def filter_current_status(self, queryset, field_name, value): if value: queryset = queryset.filter(current_status=value) return queryset def filter_role(self, queryset, field_name, value): if value: queryset = queryset.filter(roles__role__in=value, roles__end__gte=TODAY_END) return queryset def filter_region(self, queryset, field_name, value): if value == "national": return queryset elif value == "candidate_chapter": queryset = queryset.filter(chapter__candidate_chapter=True) else: queryset = queryset.filter(chapter__region__slug=value) return queryset def filter_major(self, queryset, field_name, value): if value: queryset = queryset.filter(major__major=value.major) return queryset def filter_chapter(self, queryset, field_name, value): if value: queryset = queryset.filter(chapter__slug=value) return queryset
def test_get_school_chapter_missing(): with pytest.warns(UserWarning): chapter_result = Chapter.get_school_chapter("Does not exist") assert chapter_result is None
def test_get_school_chapter(chapter): chapter_result = Chapter.get_school_chapter(chapter.school) assert chapter_result == chapter
class UserLookupForm(forms.Form): university = forms.ChoiceField(choices=Chapter.schools()) badge_number = forms.IntegerField() captcha = ReCaptchaField(label="", widget=ReCaptchaV3)
def load(self): """Load the content for a chapter. Raises: MissingRequiredFieldError: When a config (yaml) file is missing a required field. """ chapter_structure = self.load_yaml_file(self.structure_file_path) sections = chapter_structure.get("sections", None) if sections is None: raise MissingRequiredFieldError(self.structure_file_path, ["sections"], "Chapter") chapter_translations = self.get_blank_translation_dictionary() introduction_filename = "{}.md".format(self.chapter_slug) introduction_translations = self.get_markdown_translations( introduction_filename) for language, content in introduction_translations.items(): chapter_translations[language][ "introduction"] = content.html_string chapter_translations[language]["name"] = content.title chapter_icon = chapter_structure.get("icon", None) if chapter_icon is None: raise MissingRequiredFieldError(self.structure_file_path, ["icon"], "Chapter") else: # TODO: Check icon exists here before path modification # Remove directory and extension as svg templatetag automatically adds these chapter_icon = chapter_icon[4:-4] video = chapter_structure.get("video", "") if video != "" and "vimeo" not in video: raise ValueError("Video must be a Vimeo video.") # Create chapter object and save to the db chapter = Chapter(slug=self.chapter_slug, number=self.chapter_number, icon=chapter_icon, video=video) self.populate_translations(chapter, chapter_translations) self.mark_translation_availability( chapter, required_fields=["name", "introduction"]) chapter.save() self.log("Added chapter: {}".format(chapter.name)) check_interactives( introduction_translations[ get_default_language()].required_files["interactives"], self.structure_file_path, chapter, ) # Load chapter sections content_path, structure_filename = os.path.split(sections) self.factory.create_chapter_section_loader( chapter, base_path=self.base_path, content_path=os.path.join(self.content_path, content_path), structure_filename=structure_filename).load()