Exemplo n.º 1
0
class AdminUserForm(PasswordForm):

    project_manager = AutoCompleteSelectMultipleField(
        lookup_class=lookups.AssessmentLookup,
        label='Project manager',
        required=False)
    team_member = AutoCompleteSelectMultipleField(
        lookup_class=lookups.AssessmentLookup,
        label='Team member',
        required=False)
    reviewer = AutoCompleteSelectMultipleField(
        lookup_class=lookups.AssessmentLookup,
        label='Reviewer',
        required=False)

    class Meta:
        model = models.HAWCUser
        fields = (
            "email",
            "first_name",
            "last_name",
            "is_active",
            "is_staff",
            "password1",
            "password2",
            "groups",
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.id:

            self.fields['password1'].required = False
            self.fields['password2'].required = False

            self.fields['project_manager'].initial = self.instance\
                .assessment_pms.all()\
                .values_list('id', flat=True)
            self.fields['team_member'].initial = self.instance\
                .assessment_teams.all()\
                .values_list('id', flat=True)
            self.fields['reviewer'].initial = self.instance\
                .assessment_reviewers.all()\
                .values_list('id', flat=True)

    def save(self, commit=True):
        user = super().save(commit=commit)
        if user.id:
            user.assessment_pms.set(self.cleaned_data['project_manager'])
            user.assessment_teams.set(self.cleaned_data['team_member'])
            user.assessment_reviewers.set(self.cleaned_data['reviewer'])
        return user
Exemplo n.º 2
0
    class Meta:
        model = Project
        fields = [
            'title', 'looking_for_members', 'aws_resources', 'description',
            'bounty', 'technologies', 'team', 'image', 'inspiration',
            'what_it_does', 'how_it_was_built', 'challenges',
            'accomplishments', 'learned', 'whats_next'
        ]

        team = AutoCompleteSelectMultipleField(
            lookup_class=UserLookup,
            widget=AutoCompleteSelectMultipleWidget(lookup_class=UserLookup,
                                                    limit=10),
            label="Select a team member")
        bounty = AutoCompleteSelectField(lookup_class=BountyLookup,
                                         widget=AutoCompleteSelectWidget(
                                             lookup_class=BountyLookup,
                                             limit=10),
                                         label="Select a team member")
        widgets = {
            'team':
            AutoCompleteSelectMultipleWidget(lookup_class=UserLookup,
                                             limit=10),
            'bounty':
            AutoCompleteSelectWidget(lookup_class=BountyLookup, limit=10)
        }
Exemplo n.º 3
0
class ProcessedGameForm(forms.ModelForm):
    actual_instance = AutoCompleteSelectField(
        lookup_class=lookups.TournamentInstanceLookup,
        allow_new=False,
        required=True,
        widget=AutoComboboxSelectWidget,
    )
    actual_step = AutoCompleteSelectField(
        lookup_class=lookups.TournamentStepLookup,
        allow_new=False,
        required=True,
        widget=AutoComboboxSelectWidget)
    gamesheet_ds = AutoCompleteSelectField(
        lookup_class=lookups.GamesheetLookup,
        allow_new=False,
        required=True,
        widget=AutoComboboxSelectWidget)
    rating_ds = AutoCompleteSelectMultipleField(
        lookup_class=lookups.RatingsheetLookup,
        required=False,
        widget=AutoComboboxSelectMultipleWidget)

    class Media:
        js = (
            '/static/statscollect_scrap/js/instance_lookup.js',
            '/static/statscollect_scrap/js/step_lookup.js',
            '/static/statscollect_scrap/js/ratingsheet_lookup.js',
        )
Exemplo n.º 4
0
class ProjectCreateEditForm(forms.ModelForm):
    countries = AutoCompleteSelectMultipleField(lookup_class=CountryLookup)
    packages = AutoCompleteSelectMultipleField(lookup_class=PackageLookup,
                                               required=False)
    tags = AutoCompleteSelectMultipleField(lookup_class=TaxonomyLookup,
                                           required=False,
                                           label='Taxonomy')
    collaborators = AutoCompleteSelectMultipleField(lookup_class=UserLookup,
                                                    required=False)
    num_users = forms.ChoiceField(choices=Project.NUM_USERS)

    class Meta:
        model = Project
        fields = ('name', 'description', 'countries', 'tags', 'challenges',
                  'audience', 'technologies', 'metrics', 'num_users',
                  'started', 'packages', 'collaborators', 'repository_url',
                  'project_url', 'image', 'files')
Exemplo n.º 5
0
class ManyThingForm(forms.ModelForm):
    things = AutoCompleteSelectMultipleField(lookup_class=ThingLookup)

    class Meta(object):
        model = ManyThing
        fields = (
            'name',
            'things',
        )
Exemplo n.º 6
0
class ProjectForm(forms.ModelForm):
    owners = AutoCompleteSelectMultipleField(ProfileLookup)
    team_members = AutoCompleteSelectMultipleField(ProfileLookup)

    class Meta:
        model = Project
        fields = (
            'name',
            'slug',
            'description',
            'long_description',
            'image',
            'featured_image',
            'owners',
            'team_members',
            'topics',
            'tags',
            'inactive',
        )
Exemplo n.º 7
0
class CampaignAdminForm(forms.ModelForm):
    managers = AutoCompleteSelectMultipleField(
        lookup_class=OwnerLookup,
        widget=AutoCompleteSelectMultipleWidget(lookup_class=OwnerLookup),
        required=True,
    )
    class Meta(object):
        model = models.Campaign
        fields = (
            'managers', 'name', 'description', 'details', 'license', 'paypal_receiver',
            'status', 'type', 'email', 'do_watermark', 'use_add_ask', 'charitable',
        )
Exemplo n.º 8
0
class EditManagersForm(forms.ModelForm):
    managers = AutoCompleteSelectMultipleField(
            OwnerLookup,
            label='Campaign Managers',
            widget=AutoCompleteSelectMultipleWidget(OwnerLookup),
            required=True,
            error_messages = {'required': "You must have at least one manager for a campaign."},
        )
    class Meta:
        model = Campaign
        fields = ('id', 'managers')
        widgets = { 'id': forms.HiddenInput }
Exemplo n.º 9
0
class OpenCampaignForm(forms.ModelForm):
    managers = AutoCompleteSelectMultipleField(
            OwnerLookup,
            label='Campaign Managers',
            widget=AutoCompleteSelectMultipleWidget(OwnerLookup),
            required=True,
            error_messages = {'required': "You must have at least one manager for a campaign."},
        )
    userid = forms.IntegerField( required = True, widget = forms.HiddenInput )
    class Meta:
        model = Campaign
        fields = 'name', 'work',  'managers', 'type'
        widgets = { 'work': forms.HiddenInput, "name": forms.HiddenInput, }
Exemplo n.º 10
0
class MessageForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea)
    connections = AutoCompleteSelectMultipleField(
        lookup_class=ConnectionLookup)

    def __init__(self, *args, **kwargs):
        super(MessageForm, self).__init__(*args, **kwargs)
        self.fields['connections'].widget.attrs[
            'placeholder'] = 'Add a Recipient'
        self.fields['message'].widget.attrs['placeholder'] = 'Message'

    def send(self):
        message = self.cleaned_data['message']
        connections = self.cleaned_data['connections']
        return send(message, connections)
Exemplo n.º 11
0
class PackageCreateEditForm(forms.ModelForm):
    # Use a radio select field rather than the default.
    pkg_type = forms.ChoiceField(label='Package Type',
                                 widget=forms.RadioSelect,
                                 choices=Package.PACKAGE_TYPES.items(),
                                 initial=Package.APPLICATION)
    tags = AutoCompleteSelectMultipleField(lookup_class=TaxonomyLookup,
                                           required=False,
                                           label='Taxonomy')

    class Meta:
        model = Package
        fields = ('pkg_type', 'name', 'tags', 'tests_url', 'repo_url')

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

        # Package type and name are not editable once the project has been
        # created.
        if self.instance.pk:
            # self.fields.pop('pkg_type')
            self.fields.pop('name')

    def clean_name(self):
        """
        Ensure that a package with the given name is on PyPI, and add
        PyPI-derived data to the instance.

        Creates its own request to pass into update_from_pypi, in order to
        save an RTT.
        """
        name = self.cleaned_data['name']
        self.instance.name = name
        req = self.instance._get_pypi_request()
        if req.status_code >= 500:
            msg = 'PyPI appears to be down. We apologize for the inconvenience. Please retry your upload later.'
            raise forms.ValidationError(msg)
        elif req.status_code > 400:
            msg = 'Could not find this package on PyPI.'
            raise forms.ValidationError(msg)
        elif req.status_code != 200:
            msg = 'Could not validate the existence of this package.'
            raise forms.ValidationError(msg)
        self.instance.update_from_pypi(req)
        return name
Exemplo n.º 12
0
class MessageForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea)
    contacts = AutoCompleteSelectMultipleField(
        lookup_class=RecipientLookup)

    def __init__(self, *args, **kwargs):
        super(MessageForm, self).__init__(*args, **kwargs)
        self.fields['contacts'].widget.attrs['placeholder'] = 'Add a Recipient'
        self.fields['message'].widget.attrs['placeholder'] = 'Message'

    def send(self):
        message = self.cleaned_data['message']
        contacts = self.cleaned_data['contacts']
        recipients = [recipient.hl_contact for recipient in contacts]
        api.send_sms(body=message,
                     from_phone='Info',
                     to=recipients)
        return recipients
Exemplo n.º 13
0
class SimpleForm(forms.Form):
    "Non-model form usage."
    thing = AutoCompleteSelectField(lookup_class=ThingLookup)
    new_thing = AutoCompleteSelectField(lookup_class=ThingLookup,
                                        allow_new=True)
    things = AutoCompleteSelectMultipleField(lookup_class=ThingLookup)
Exemplo n.º 14
0
class ChangesetForm(forms.ModelForm):
    """
    Form for creating or editing a Changeset.

    Uses django-selectable for autocompleting selection of registration centers,
    and some javascript in the page to implement custom behavior as the user
    changes their choices.
    """
    selected_centers = AutoCompleteSelectMultipleField(
        help_text=_("Start typing registration center name to add to list"),
        label=_("Selected centers"),
        lookup_class=RegistrationCenterLookup,
        required=False,
    )

    target_center = AutoCompleteSelectField(
        help_text=_("Start typing registration center name to choose"),
        lookup_class=RegistrationCenterLookup,
        required=False,
    )

    upload_file = forms.FileField(
        required=False,
        help_text=
        _("Upload text file with one NID per line, and no headers or punctuation."
          ))

    okay_to_remove_approvals = forms.BooleanField(
        required=True,
        help_text=
        _("This changeset has one or more approvals. If you change the changeset, "
          "the approvals will be revoked and the changeset will have to be approved "
          "again. If you want to do that, check here. If not, cancel, or go to "
          "another page without submitting your changes."))

    # Django will add this class to required fields.
    # Starting in Django 1.8, it'll add it to their labels too, but we're
    # still on 1.7 so we'll have to do it in the template.
    required_css_class = 'requiredField'

    class Meta(object):
        fields = [
            'name',
            'change',
            'how_to_select',
            'upload_file',
            'selected_centers',
            'other_changeset',
            'target_center',
            'message',
            'justification',
        ]
        model = Changeset

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(ChangesetForm, self).__init__(*args, **kwargs)
        self.citizens = []  # Citizens from uploaded file

        # If there are no approvals or no changeset yet,
        # remove the 'okay_to_remove_approvals' field
        if not (self.instance and self.instance.number_of_approvals):
            del self.fields['okay_to_remove_approvals']

    def clean_other_changeset(self):
        """Ensure other_changeset is provided if needed, and in an acceptable status"""
        data = self.cleaned_data
        other_changeset = data.get('other_changeset', None)
        if (data['how_to_select'] == Changeset.SELECT_OTHER_CHANGESET
                and not other_changeset):
            raise ValidationError(_("No other changeset selected"))
        if data['change'] == Changeset.CHANGE_ROLLBACK:
            if not other_changeset:
                raise ValidationError(_("No other changeset selected"))
            if other_changeset.status not in (
                    Changeset.STATUS_SUCCESSFUL,
                    Changeset.STATUS_PARTIALLY_SUCCESSFUL):
                raise ValidationError(
                    _("Only successful changesets can be rolled back."))
        return other_changeset

    def clean_selected_centers(self):
        """Ensure selected_centers are provided if needed"""
        data = self.cleaned_data
        if data['how_to_select'] == Changeset.SELECT_CENTERS and not data[
                'selected_centers']:
            raise ValidationError(_("No centers selected"))
        return data['selected_centers']

    def clean_target_center(self):
        """Ensure target center is provided if needed, and is not one of the source centers"""
        data = self.cleaned_data
        if data['change'] == Changeset.CHANGE_CENTER:
            if not data['target_center']:
                raise ValidationError(_("No target center selected"))
            if (data['how_to_select'] == Changeset.SELECT_CENTERS
                    and data['target_center'] in data.get(
                        'selected_centers', [])):
                raise ValidationError(
                    _("Target center is one of the centers being moved from"))
        return data['target_center']

    def clean_upload_file(self):
        """Handle uploading a file of NIDs. Will validate the input, look up the citizens, and
        set self.citizens to a list of the Citizen objects they chose."""
        data = self.cleaned_data
        if data['how_to_select'] == Changeset.SELECT_UPLOADED_NIDS:
            uploaded_file = data['upload_file']
            if not uploaded_file:
                if self.instance.pk and self.instance.uploaded_citizens.exists(
                ):
                    # It's okay not to re-upload citizens, we already have some
                    return
                raise ValidationError(
                    _("An uploaded file is required if selection method is uploaded NIDs"
                      ))
            errors = []
            for i, line in enumerate(uploaded_file):
                line_number = i + 1  # Humans start counting at 1, not 0
                if len(errors) >= MAX_ERRORS:
                    errors.append(
                        _("Stopping after {number} errors.").format(
                            number=len(errors)))
                    break
                line = line.strip()
                if not line:
                    # Allow and ignore blank lines
                    continue
                if len(line) != NID_LENGTH:
                    errors.append(
                        _("Line {number}: Wrong length").format(
                            number=line_number))
                    continue
                try:
                    num = int(line)
                except (ValueError, TypeError):
                    errors.append(
                        _("Line {number}: Not a valid number").format(
                            number=line_number))
                    continue
                if line[0] not in ['1', '2']:
                    errors.append(
                        _("Line {number}: Not a valid national ID number").
                        format(number=line_number))
                    continue
                citizen = get_citizen_by_national_id(num)
                if not citizen:
                    errors.append(
                        _("Line {number}: No person registered with that NID").
                        format(number=line_number))
                    continue
                self.citizens.append(citizen)
            if errors:
                raise ValidationError(". ".join(errors))
        return data['upload_file']

    def save(self, *args, **kwargs):
        """
        Save the Changeset, and set selected_citizens based on self.citizens
        """
        # If new, remember who created it
        if not self.instance.pk:
            self.instance.created_by = self.request.user
        changeset = super(ChangesetForm, self).save(*args, **kwargs)
        if changeset.pk:
            # Remove any citizens from a previous edit that are no longer on the list.
            citizens_to_remove = set(changeset.selected_citizens.all()) - set(
                self.citizens)
            changeset.selected_citizens.remove(*citizens_to_remove)
            # Add any new ones
            citizens_to_add = set(self.citizens) - set(
                changeset.selected_citizens.all())
            changeset.selected_citizens.add(*citizens_to_add)
        # If there were any approvals, remove them (and update status)
        for approving_user in changeset.approvers.all():
            changeset.revoke_approval(approving_user)
            if self.request:
                messages.info(
                    self.request,
                    _("Approval of {user} removed due to changes").format(
                        user=approving_user))
        return changeset
Exemplo n.º 15
0
class PatientRemindersForm(forms.ModelForm):

    first_name = forms.CharField(max_length=64, required=False)
    last_name = forms.CharField(max_length=64, required=False)
    reminders = AutoCompleteSelectMultipleField(
        ReminderLookup,
        label="Medicine Reminders",
        required=False,
        widget=AutoComboboxSelectMultipleWidget)
    feeds = AutoCompleteSelectMultipleField(
        FeedLookup, required=False, widget=AutoComboboxSelectMultipleWidget)
    queries = AutoCompleteSelectMultipleField(
        QueryLookup, required=False, widget=AutoComboboxSelectMultipleWidget)

    class Meta(object):
        model = patients.Patient
        fields = ('subject_number', 'first_name', 'last_name', 'mobile_number',
                  'pin', 'next_visit', 'reminder_time', 'daily_doses',
                  'wisepill_msisdn', 'manual_adherence')

    def __init__(self, *args, **kwargs):
        super(PatientRemindersForm, self).__init__(*args, **kwargs)
        self.fields['mobile_number'].widget = FancyPhoneInput()
        self.fields['next_visit'].widget.attrs.update({'class': 'datepicker'})
        self.fields['reminder_time'].widget.attrs.update(
            {'class': 'timepicker'})
        self.fields['reminder_time'].label = 'Appointment Reminder Time'
        if self.instance and self.instance.pk:
            self.initial['reminders'] = self.instance.contact.reminders.all()
            self.initial['feeds'] = self.instance.contact.feeds.all()
            self.initial['first_name'] = self.instance.contact.first_name
            self.initial['last_name'] = self.instance.contact.last_name
            self.initial[
                'queries'] = self.instance.adherence_query_schedules.all()
        else:
            # Generate subject ID and pin
            self.initial['subject_number'] = self.generate_new_subject_id()
            self.initial['pin'] = self.generate_new_pin()

    def clean_mobile_number(self):
        mobile_number = normalize_number(self.cleaned_data['mobile_number'])
        validate_phone(mobile_number)
        return mobile_number

    def clean_manual_adherence(self):
        return self.cleaned_data.get('manual_adherence', 0) or 0

    def generate_new_subject_id(self):
        valid = False
        while not valid:
            start = ''.join([random.choice(string.digits) for i in range(3)])
            end = ''.join([random.choice(string.digits) for i in range(5)])
            test = '%s-%s' % (start, end)
            valid = not patients.Patient.objects.filter(
                subject_number=test).exists()
        return test

    def generate_new_pin(self):
        return ''.join([random.choice(string.digits) for i in range(4)])

    def save(self, *args, **kwargs):
        patient = super(PatientRemindersForm, self).save(commit=False)
        if not patient.contact_id:
            contact, _ = Contact.objects.get_or_create(
                name=patient.subject_number)
            patient.contact = contact
        first_name = self.cleaned_data.get('first_name', '')
        if first_name:
            patient.contact.first_name = first_name
        last_name = self.cleaned_data.get('last_name', '')
        if last_name:
            patient.contact.last_name = last_name
        patient.contact.phone = patient.mobile_number
        patient.contact.pin = patient.pin
        commit = kwargs.pop('commit', True)
        if commit:
            patient.contact.save()
            reminders = self.cleaned_data.get('reminders', []) or []
            patient.contact.reminders.clear()
            for r in reminders:
                r.recipients.add(patient.contact)
            feeds = self.cleaned_data.get('feeds', []) or []
            patient.contact.feeds.clear()
            for f in feeds:
                f.subscribers.add(patient.contact)
            patient.save()
            queries = self.cleaned_data.get('queries', []) or []
            patient.adherence_query_schedules.clear()
            for q in queries:
                q.patients.add(patient)
        return patient