<commit_before>from django import forms
from .models import LeafPack, LeafPackType, Macroinvertebrate, LeafPackBug, LeafPackSensitivityGroup
from dataloaderinterface.models import SiteRegistration
from django.core.exceptions import ObjectDoesNotExist


class MDLCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
    template_name = 'mdl-checkbox-select-multiple.html'

    def render(self, name, value, attrs=None, renderer=None):
        context = self.get_context(name, value, attrs)
        context['choices'] = [choice[1][0] for choice in context['widget']['optgroups']]
        context['name'] = name
        return self._render(self.template_name, context, renderer)


class LeafPackForm(forms.ModelForm):

    DEPLOYMENT_TYPE_CHOICES = (('Pool', 'Pool'), ('Riffle', 'Riffle'), ('Run', 'Run'))

    def __init__(self, *args, **kwargs):
        super(LeafPackForm, self).__init__(*args, **kwargs)
        if self.instance is not None and self.instance.pk is not None:
            other_types = self.instance.types.all().filter(created_by__isnull=False)
            self.initial['types_other'] = ', '.join([other.name for other in other_types])

    def save(self, commit=True):
        super(LeafPackForm, self).save(commit=commit)

        # LeafPackTypes from the cleaned form data. These types may or may not exist (i.e. they were created by a user)
        types_other_cleaned = self.cleaned_data.get('types_other', '').split(',')

        for other in types_other_cleaned:
            # remove leading/trailing white space
            other = other.strip()

            try:
                # if the type doesn't exist, skip over it since it's 'created_by' value will be empty
                lptype = LeafPackType.objects.get(name=other)
                self.instance.types.add(lptype)
            except ObjectDoesNotExist:
                continue

        self.instance.save()

    def clean(self):
        cleaned_data = super(LeafPackForm, self).clean()
        retrieval_count = cleaned_data.get('leafpack_retrieval_count', 0)
        placement_count = cleaned_data.get('leafpack_placement_count', 0)

        if retrieval_count > placement_count:
            self.add_error('leafpack_retrieval_count', forms.ValidationError(
                'The number of packs retrieved cannot exceed the number of packs placed!'))

        return self.cleaned_data

    site_registration = forms.ModelChoiceField(
        widget=forms.HiddenInput,
        queryset=SiteRegistration.objects.all()
    )

    types = forms.ModelMultipleChoiceField(
        widget=MDLCheckboxSelectMultiple,
        label='Enter the three predominant leaf species:',
        queryset=LeafPackType.objects.filter(created_by=None),
    )

    types_other = forms.CharField(
        max_length=255,
        label='Enter leaf species not listed above or experimental materials such as newspaper, plastic, etc.:',
        required=False,
        widget=forms.TextInput(attrs={'placeholder': 'i.e., Species 1, Species 2, Species 3'})<commit_msg>allow leaf species not selected<commit_after>from django import forms
from .models import LeafPack, LeafPackType, Macroinvertebrate, LeafPackBug, LeafPackSensitivityGroup
from dataloaderinterface.models import SiteRegistration
from django.core.exceptions import ObjectDoesNotExist


class MDLCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
    template_name = 'mdl-checkbox-select-multiple.html'

    def render(self, name, value, attrs=None, renderer=None):
        context = self.get_context(name, value, attrs)
        context['choices'] = [choice[1][0] for choice in context['widget']['optgroups']]
        context['name'] = name
        return self._render(self.template_name, context, renderer)


class LeafPackForm(forms.ModelForm):

    DEPLOYMENT_TYPE_CHOICES = (('Pool', 'Pool'), ('Riffle', 'Riffle'), ('Run', 'Run'))

    def __init__(self, *args, **kwargs):
        super(LeafPackForm, self).__init__(*args, **kwargs)
        if self.instance is not None and self.instance.pk is not None:
            other_types = self.instance.types.all().filter(created_by__isnull=False)
            self.initial['types_other'] = ', '.join([other.name for other in other_types])

    def save(self, commit=True):
        super(LeafPackForm, self).save(commit=commit)

        # LeafPackTypes from the cleaned form data. These types may or may not exist (i.e. they were created by a user)
        types_other_cleaned = self.cleaned_data.get('types_other', '').split(',')

        for other in types_other_cleaned:
            # remove leading/trailing white space
            other = other.strip()

            try:
                # if the type doesn't exist, skip over it since it's 'created_by' value will be empty
                lptype = LeafPackType.objects.get(name=other)
                self.instance.types.add(lptype)
            except ObjectDoesNotExist:
                continue

        self.instance.save()

    def clean(self):
        cleaned_data = super(LeafPackForm, self).clean()
        retrieval_count = cleaned_data.get('leafpack_retrieval_count', 0)
        placement_count = cleaned_data.get('leafpack_placement_count', 0)

        if retrieval_count > placement_count:
            self.add_error('leafpack_retrieval_count', forms.ValidationError(
                'The number of packs retrieved cannot exceed the number of packs placed!'))

        return self.cleaned_data

    site_registration = forms.ModelChoiceField(
        widget=forms.HiddenInput,
        queryset=SiteRegistration.objects.all()
    )

    types = forms.ModelMultipleChoiceField(
        widget=MDLCheckboxSelectMultiple,
        label='Enter the three predominant leaf species:',
        required=False,
        queryset=LeafPackType.objects.filter(created_by=None),
    )

    types_other = forms.CharField(
        max_length=255,
        label='Enter leaf species not listed above or experimental materials such as newspaper, plastic, etc.:',
        required=False,
        widget=forms.TextInput(attrs={'placeholder': 'i.e., Species 1, Species 2, Species 3'})
{'fraction_non_alphanumeric': 0.10167267956707117, 'fraction_numerical': 0.0032797638570022957, 'mean_word_length': 3.2120165745856353, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7519242', 'n_tokens_mistral': 1779, 'n_tokens_neox': 1684, 'n_words': 428}