class Meta: model = TModel fields = ('name', 'checkbox', 'owner', 'test') widgets = { 'test': autocomplete.ModelSelect2(url='linked_data_rf', forward=(forward.Field(src="checkbox"), forward.Field(src="owner", dst="possessor"), forward.Const(val=42, dst="secret"))) }
class TagForm(forms.Form): """This form allows the selection of a tag""" tag_select = forms.ModelChoiceField( queryset=Tag.objects.all(), label=" ", required=False, widget=autocomplete.ModelSelect2( url="tag-autocomplete", attrs={"data-placeholder": "Search tags"}, forward=(forward.Const(True, "slug"), ), ), )
class Meta: model = GeneListNode fields = ("pathology_test_version", "sample", "exclude", "accordion_panel") widgets = { "pathology_test_version": autocomplete.ModelSelect2( url='pathology_test_version_autocomplete', attrs={'data-placeholder': 'Pathology Test...'}, forward=(forward.Const(True, "active"), )), 'accordion_panel': HiddenInput(), }
class ExemptionFilterSet(django_filters.FilterSet): """Allows exemptions to be filtered by jurisdiction""" jurisdiction = django_filters.ModelChoiceFilter( label="Jurisdiction", queryset=Jurisdiction.objects.filter(level__in=("s", "f"), hidden=False), widget=autocomplete.ModelSelect2( url="jurisdiction-autocomplete", attrs={"data-placeholder": "Search for jurisdiction"}, forward=(forward.Const(["s", "f"], "levels"),), ), ) class Meta: model = Exemption fields = ["jurisdiction"]
class ProxyFilterSet(django_filters.FilterSet): """Allows proxies to be filtered by location.""" location = django_filters.ModelMultipleChoiceFilter( label="State", queryset=Jurisdiction.objects.filter(level="s", hidden=False), widget=autocomplete.ModelSelect2Multiple( url="jurisdiction-autocomplete", attrs={"data-placeholder": "Search for state"}, forward=(forward.Const(["s"], "levels"), ), ), ) class Meta: model = Profile fields = ["location"]
class ProjectManagerForm(forms.Form): """Form for managing a list of projects""" projects = forms.ModelMultipleChoiceField( required=False, queryset=Project.objects.none(), widget=autocomplete.ModelSelect2Multiple( url="project-autocomplete", attrs={"placeholder": "Search for a project"}, forward=(forward.Const(True, "manager"), ), ), ) def __init__(self, *args, **kwargs): user = kwargs.pop("user") super(ProjectManagerForm, self).__init__(*args, **kwargs) self.fields["projects"].queryset = Project.objects.get_manager(user)
class JurisdictionFilterSet(django_filters.FilterSet): """Allows jurisdiction to be filtered by level of government and state.""" level = django_filters.ChoiceFilter(choices=LEVELS) parent = django_filters.ModelChoiceFilter( label="State", queryset=Jurisdiction.objects.filter(level="s", hidden=False), widget=autocomplete.ModelSelect2( url="jurisdiction-autocomplete", attrs={"data-placeholder": "Search for state"}, forward=(forward.Const(["s"], "levels"),), ), ) class Meta: model = Jurisdiction fields = ["level", "parent"]
class AgencyAdminForm(forms.ModelForm): """Agency admin form to order users""" user = forms.ModelChoiceField( queryset=User.objects.all(), required=False, widget=autocomplete.ModelSelect2( url="user-autocomplete", attrs={"data-placeholder": "User?", "data-width": None}, ), ) jurisdiction = forms.ModelChoiceField( queryset=Jurisdiction.objects.filter(hidden=False), widget=autocomplete.ModelSelect2( url="jurisdiction-autocomplete", attrs={"data-placeholder": "Jurisdiction?", "data-width": None}, ), ) appeal_agency = forms.ModelChoiceField( queryset=Agency.objects.all(), required=False, widget=autocomplete.ModelSelect2( url="agency-autocomplete", forward=("jurisdiction", forward.Const(True, "appeal")), attrs={"data-placeholder": "Agency?", "data-width": None}, ), ) parent = forms.ModelChoiceField( queryset=Agency.objects.all(), required=False, widget=autocomplete.ModelSelect2( url="agency-autocomplete", forward=("jurisdiction",), attrs={"data-placeholder": "Agency?", "data-width": None}, ), ) class Meta: model = Agency fields = "__all__"
class ArticleDateRangeFilterSet(django_filters.FilterSet): """Allows a list of news items to be filtered by a date range, an author, or many tags.""" projects = django_filters.ModelMultipleChoiceFilter( field_name="projects", queryset=lambda request: Project.objects.get_visible(request.user), widget=autocomplete.ModelSelect2Multiple( url="project-autocomplete", attrs={"data-placeholder": "Search projects"}), ) authors = django_filters.ModelMultipleChoiceFilter( queryset=(User.objects.annotate( article_count=Count("authored_articles")).filter( article_count__gt=0)), widget=autocomplete.ModelSelect2Multiple( url="user-autocomplete", attrs={"data-placeholder": "Search authors"}, forward=(forward.Const(True, "authors"), ), ), ) pub_date = django_filters.DateFromToRangeFilter( label="Date Range", lookup_expr="contains", widget=RangeWidget(attrs={ "class": "datepicker", "placeholder": "MM/DD/YYYY" }), ) tags = django_filters.ModelMultipleChoiceFilter( field_name="tags__name", queryset=Tag.objects.all(), label="Tags", widget=autocomplete.ModelSelect2Multiple( url="tag-autocomplete", attrs={"data-placeholder": "Search tags"}), ) class Meta: model = Article fields = ["projects", "authors", "pub_date"]
class Meta: model = models.Product fields = '__all__' widgets_dict = SeoFormMixin.Meta.widgets widgets_dict.update({ 'parent': autocomplete.ModelSelect2( url='product-autocomplete', forward=( forward.Field('slug', 'exclude_slug'), forward.Const([PRODUCT_WITH_VARIANTS], 'filter_sub_types'), )), 'short_description_ru': CKEditorWidget, 'short_description_uk': CKEditorWidget, 'full_description_ru': CKEditorWidget, 'full_description_uk': CKEditorWidget, }) widgets = widgets_dict
class GearArticleForm(forms.ModelForm): name = forms.CharField(label="Article Title") file = forms.FileField( required=False, help_text= "You can optionally attach your article or supporting documents", ) authors = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=autocomplete.ModelSelect2Multiple(url="users:autocomplete", forward=(forward.Const( "true", "chapter"), )), ) class Meta: model = GearArticle fields = [ "name", "authors", "article", "file", ]
class SnailMailTaskFilterSet(TaskFilterSet): """Allows snail mail tasks to be filtered by category, as well as the presence of a tracking number or an agency note.""" category = django_filters.ChoiceFilter(choices=[("", "All")] + SNAIL_MAIL_CATEGORIES) has_address = django_filters.ChoiceFilter(method="filter_has_address", label="Has address", choices=BOOLEAN_CHOICES) has_attachments = django_filters.ChoiceFilter( method="filter_has_attachments", label="Has attachments", choices=BOOLEAN_CHOICES, ) has_tracking_number = django_filters.ChoiceFilter( method="filter_has_tracking_number", label="Has tracking number", choices=BOOLEAN_CHOICES, ) has_agency_notes = django_filters.ChoiceFilter( method="filter_has_agency_notes", label="Has agency notes", choices=BOOLEAN_CHOICES, ) resolved = django_filters.BooleanFilter(label="Show Resolved", widget=forms.CheckboxInput()) resolved_by = django_filters.ModelMultipleChoiceFilter( queryset=User.objects.all(), widget=autocomplete.ModelSelect2Multiple( url="user-autocomplete", attrs={"data-placeholder": "Search users"}, forward=(forward.Const(True, "tasks"), ), ), ) def blank_choice(self, queryset, name, value): """Check if the value is blank""" if value == "True": return queryset.exclude(**{name: ""}) elif value == "False": return queryset.filter(**{name: ""}) return queryset def filter_has_address(self, queryset, name, value): """Check if the foia has an address.""" # pylint: disable=unused-argument if value == "True": return queryset.exclude(communication__foia__address=None) else: return queryset.filter(communication__foia__address=None) def filter_has_attachments(self, queryset, name, value): """Check if the communication has attachments.""" # pylint: disable=unused-argument if value == "True": return queryset.exclude(communication__files=None) else: return queryset.filter(communication__files=None) def filter_has_tracking_number(self, queryset, name, value): """Check if the foia has a tracking number.""" # pylint: disable=unused-argument if value == "True": return queryset.exclude(communication__foia__tracking_ids=None) else: return queryset.filter(communication__foia__tracking_ids=None) def filter_has_agency_notes(self, queryset, name, value): """Check if the agency has notes.""" # pylint: disable=unused-argument return self.blank_choice(queryset, "communication__foia__agency__notes", value) class Meta: model = SnailMailTask fields = [ "category", "has_address", "has_attachments", "has_tracking_number", "has_agency_notes", "resolved", "resolved_by", ]
def __init__(self, *args, brand, **kwargs): super().__init__(*args, **kwargs) if brand is not None: self.fields['product'].queryset = brand.product_set.all() self.fields['product'].widget.forward = [ forward.Const(brand.pk, 'brand')]
class GeneListNodeForm(BaseNodeForm): custom_gene_list_text = forms.CharField( widget=forms.Textarea(attrs={'placeholder': 'Gene names...'}), required=False) gene_list = forms.ModelMultipleChoiceField( required=False, queryset=GeneList.objects.all(), widget=ModelSelect2Multiple(url='category_gene_list_autocomplete', attrs={'data-placeholder': 'Gene List...'}, forward=(forward.Const(None, 'category'), ))) panel_app_panel_aus = forms.ModelMultipleChoiceField( required=False, queryset=PanelAppPanel.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='panel_app_panel_aus_autocomplete', attrs={ 'data-placeholder': 'Australian Genomics PanelApp panel...' })) panel_app_panel_eng = forms.ModelMultipleChoiceField( required=False, queryset=PanelAppPanel.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='panel_app_panel_eng_autocomplete', attrs={'data-placeholder': 'Genomics England PanelApp panel...'})) class Meta: model = GeneListNode fields = ("pathology_test_version", "sample", "exclude", "accordion_panel") widgets = { "pathology_test_version": autocomplete.ModelSelect2( url='pathology_test_version_autocomplete', attrs={'data-placeholder': 'Pathology Test...'}, forward=(forward.Const(True, "active"), )), 'accordion_panel': HiddenInput(), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) samples_queryset = Sample.objects.filter( pk__in=self.instance.get_sample_ids()) self.fields['sample'].queryset = samples_queryset def save(self, commit=True): node = super().save(commit=False) custom_gene_list_text = self.cleaned_data["custom_gene_list_text"] if custom_gene_list_text is not None: md5_hash = md5sum_str(custom_gene_list_text) if node.custom_text_gene_list: custom_text_gene_list = node.custom_text_gene_list if custom_text_gene_list.md5_hash != md5_hash: custom_text_gene_list.md5_hash = 'deleted_will_regen' if custom_text_gene_list.gene_list is not None: custom_text_gene_list.gene_list.delete() custom_text_gene_list.gene_list = None custom_text_gene_list.gene_list = None else: custom_text_gene_list = CustomTextGeneList() #logging.debug("gene_list is currently %s", custom_text_gene_list.gene_list) custom_text_gene_list.name = f"Node_{self.instance.pk}_custom" custom_text_gene_list.text = custom_gene_list_text custom_text_gene_list.save() create_custom_text_gene_list(custom_text_gene_list, self.instance.analysis.user.username, GeneListCategory.NODE_CUSTOM_TEXT, hidden=True) node.custom_text_gene_list = custom_text_gene_list # TODO: I'm sure there's a way to get Django to handle this via save_m2m() gl_set = node.genelistnodegenelist_set gl_set.all().delete() for gene_list in self.cleaned_data["gene_list"]: gl_set.create(gene_list=gene_list) # PanelAppPanel app objects are the same pap_set = node.genelistnodepanelapppanel_set pap_set.all().delete() for form_name in ["panel_app_panel_aus", "panel_app_panel_eng"]: for pap in self.cleaned_data[form_name]: pap_set.create(panel_app_panel=pap) # Make sure that if we select sample qc gene list if sample := self.cleaned_data["sample"]: node._set_sample(sample) if commit: node.save() return node
def __init__(self, *args, **kwargs): genome_build = kwargs.pop("genome_build", None) super().__init__(*args, **kwargs) if genome_build: self.fields["cohort"].widget.forward.append( forward.Const(genome_build.pk, "genome_build_id"))
def __init__(self, *args, **kwargs): self.question_id = kwargs.pop('question_id') super(MetaFieldForm, self).__init__(*args, **kwargs) question = Question.objects.get(id=self.question_id) qs = Institution.objects.exclude(id__in=[inst.id for inst in question.institution.all()]) self.fields['institution'] = forms.ModelMultipleChoiceField( queryset=qs, widget=autocomplete.ModelSelect2Multiple( url='institution-autocomplete', forward=( forward.Const(self.question_id, 'question_id'), ) ), label='Voeg toe', required=False ) self.fields['institution_delete'].queryset = question.institution self.fields['promotor'] = forms.ModelMultipleChoiceField( queryset=Promotor.objects.all(), required=False, label='Voeg toe', widget=autocomplete.ModelSelect2Multiple( url='promotor-autocomplete', forward=( forward.Const(self.question_id, 'question_id'), 'institution', ) ) ) self.fields['promotor_delete'].queryset = question.promotor self.fields['faculty'] = forms.ModelMultipleChoiceField( queryset=Faculty.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='faculty-autocomplete', forward=(forward.Const(self.question_id, 'question_id'), 'institution', ) ), label='Voeg toe', required=False) self.fields['faculty_new'] = forms.CharField(max_length=33, required=False, label="Niet in de lijst?") self.fields['faculty_delete'] = forms.ModelMultipleChoiceField( queryset=question.faculty.all(), widget=forms.CheckboxSelectMultiple(), label='Verwijderen:', required=False ) self.fields['education'] = forms.ModelMultipleChoiceField( queryset=Education.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='education-autocomplete', forward=(forward.Const(self.question_id, 'question_id'), 'faculty', 'institution', ) ), label='Voeg toe', required=False) self.fields['education_delete'].queryset = question.education self.fields['subject'] = forms.ModelMultipleChoiceField( queryset=QuestionSubject.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='subject-autocomplete', forward=(forward.Const(self.question_id, 'question_id'), 'education', ) ), label='Voeg toe', required=False) self.fields['subject_delete'].queryset = question.question_subject
class CrowdsourceForm(forms.ModelForm, CrowdsourceDataCsvForm): """Form for creating a crowdsource""" prefix = "crowdsource" project = forms.ModelChoiceField( queryset=Project.objects.none(), required=False, widget=autocomplete.ModelSelect2( url="project-autocomplete", attrs={"data-placeholder": "Search projects"}, forward=(forward.Const(True, "manager"), ), ), ) form_json = forms.CharField(widget=forms.HiddenInput(), initial="[]") submission_emails = forms.CharField( help_text="Comma seperated list of emails to send to on submission", required=False, ) class Meta: model = Crowdsource fields = ( "title", "project", "description", "data_limit", "user_limit", "registration", "form_json", "data_csv", "multiple_per_page", "project_only", "project_admin", "submission_emails", "ask_public", ) def __init__(self, *args, **kwargs): user = kwargs.pop("user") super(CrowdsourceForm, self).__init__(*args, **kwargs) self.fields["data_csv"].required = False if not user.profile.is_advanced: del self.fields["registration"] self.fields["project"].queryset = Project.objects.get_manager(user) def clean_form_json(self): """Ensure the form JSON is in the correct format""" # pylint: disable=too-many-branches form_json = self.cleaned_data["form_json"] try: form_data = json.loads(form_json) except ValueError: raise forms.ValidationError("Invalid form data: Invalid JSON") if not isinstance(form_data, list): raise forms.ValidationError("Invalid form data: Not a list") if form_data == []: raise forms.ValidationError( "Having at least one field on the form is required") for data in form_data: label = data.get("label") if not label: raise forms.ValidationError("Invalid form data: Missing label") required = data.get("required", False) if required not in [True, False]: raise forms.ValidationError( "Invalid form data: Invalid required") type_ = data.get("type") if not type_: raise forms.ValidationError( "Invalid form data: Missing type for {}".format(label)) if type_ not in FIELD_DICT: raise forms.ValidationError( "Invalid form data: Bad type {}".format(type_)) field = FIELD_DICT[type_] if field.accepts_choices and "values" not in data: raise forms.ValidationError( "Invalid form data: {} requires choices".format(type_)) if field.accepts_choices and "values" in data: for value in data["values"]: choice_label = value.get("label") if not choice_label: raise forms.ValidationError( "Invalid form data: Missing label for " "choice of {}".format(label)) choice_value = value.get("value") if not choice_value: raise forms.ValidationError( "Invalid form data: Missing value for " "choice {} of {}".format(choice_label, label)) return form_json def clean_submission_emails(self): """Validate the submission emails field""" return EmailAddress.objects.fetch_many( self.cleaned_data["submission_emails"], ignore_errors=False)
def __init__(self, **kwargs): event = kwargs.pop('event') super().__init__(**kwargs) self.fields['user'].widget.forward = [ forward.Const(event.id, 'event_id') ]