コード例 #1
0
 def test_clean(self):
     ContactFormset = formset_factory(form=ContactsForm)
     value = ContactFormset({
         'form-TOTAL_FORMS': '2',
         'form-INITIAL_FORMS': '1',
         'form-MAX_NUM_FORMS': '0',
         'form-MAX_NUM_FORMS': '1000',
         'form-0-name': 'Ringo',
         'form-0-email': '*****@*****.**',
         'form-0-tel': '555-555',
         'form-1-name': 'john',
         'form-1-email': '*****@*****.**',
         'form-1-tel': '555-555',
         'form-1-remove': True,
         'form-2-name': '',
         'form-2-email': '',
         'form-2-tel': '',
     })
     field = org_fields.ContactsField(form=ContactsForm)
     expected = [{
         'name': 'Ringo',
         'email': '*****@*****.**',
         'tel': '555-555'
     }]
     assert field.clean(value) == expected
コード例 #2
0
ファイル: forms.py プロジェクト: williemwewa/cadasta-platform
class ProjectAddDetails(SanitizeFieldsForm, forms.Form):
    class Media:
        js = ('js/file-upload.js', 'js/sanitize.js')

    organization = forms.ChoiceField()
    name = forms.CharField(max_length=100)
    description = forms.CharField(required=False, widget=forms.Textarea)
    access = org_fields.PublicPrivateField(initial='public')
    url = forms.URLField(required=False)
    questionnaire = forms.CharField(required=False,
                                    widget=S3FileUploadWidget(
                                        upload_to='xls-forms',
                                        accepted_types=QUESTIONNAIRE_TYPES))
    original_file = forms.CharField(required=False,
                                    max_length=200,
                                    widget=forms.HiddenInput)
    contacts = org_fields.ContactsField(form=ContactsForm, required=False)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        org_is_chosen = kwargs.pop('org_is_chosen', None)
        super().__init__(*args, **kwargs)

        if self.user.is_superuser:
            self.orgs = Organization.objects.filter(
                archived=False).order_by('name')
        else:
            qs = self.user.organizations.filter(
                archived=False).order_by('name')
            self.orgs = [
                o for o in qs
                if check_perms(self.user, ('project.create', ), (o, ))
            ]
        choices = [(o.slug, o.name) for o in self.orgs]
        if not org_is_chosen and len(choices) > 1:
            choices = [('', _("Please select an organization"))] + choices
        self.fields['organization'].choices = choices

    def clean_name(self):
        name = self.cleaned_data['name']

        # Check that name is not restricted
        invalid_names = settings.CADASTA_INVALID_ENTITY_NAMES
        if slugify(name, allow_unicode=True) in invalid_names:
            raise forms.ValidationError(
                _("Project name cannot be “Add” or “New”."))

        # Check that name is unique org-wide
        # (Explicit validation because we are using a wizard and the
        # unique_together validation cannot occur in the proper page)
        if self.cleaned_data.get('organization'):
            not_unique = Project.objects.filter(name__iexact=name).exists()
            if not_unique:
                raise forms.ValidationError(
                    _("Project with this name already exists"))

        return name
コード例 #3
0
ファイル: forms.py プロジェクト: williemwewa/cadasta-platform
class OrganizationForm(SanitizeFieldsForm, forms.ModelForm):
    urls = pg_forms.SimpleArrayField(
        forms.URLField(required=False),
        required=False,
        error_messages={'item_invalid': ""},
    )
    contacts = org_fields.ContactsField(form=ContactsForm, required=False)
    access = org_fields.PublicPrivateField()

    class Meta:
        model = Organization
        fields = ['name', 'description', 'urls', 'contacts', 'access']

    class Media:
        js = ('js/file-upload.js', 'js/sanitize.js')

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        self.fields['name'].error_messages['unique'] = _(
            "Organization with this name already exists.")

    def clean_name(self):
        name = self.cleaned_data['name']
        invalid_names = settings.CADASTA_INVALID_ENTITY_NAMES
        if slugify(name, allow_unicode=True) in invalid_names:
            raise forms.ValidationError(
                _("Organization name cannot be “Add” or “New”."))

        is_create = not self.instance.id
        queryset = Organization.objects.filter(name__iexact=name)
        if is_create:
            not_unique = queryset.exists()
        else:
            not_unique = queryset.exclude(id=self.instance.id).exists()
        if not_unique:
            raise forms.ValidationError(
                self.fields['name'].error_messages['unique'])

        return name

    def save(self, *args, **kwargs):
        instance = super().save(commit=False)
        is_create = not instance.id

        instance.save()

        if is_create:
            OrganizationRole.objects.create(organization=instance,
                                            user=self.user,
                                            admin=True)

        return instance
コード例 #4
0
 def test_invalid_clean(self):
     ContactFormset = formset_factory(form=ContactsForm)
     value = ContactFormset({
         'form-TOTAL_FORMS': '2',
         'form-INITIAL_FORMS': '1',
         'form-MAX_NUM_FORMS': '0',
         'form-MAX_NUM_FORMS': '1000',
         'form-0-name': 'Ringo',
         'form-0-email': 'ringo@beatles',
         'form-0-tel': '',
         'form-1-name': '',
         'form-1-email': '',
         'form-1-tel': ''
     })
     field = org_fields.ContactsField(form=ContactsForm)
     with raises(ValidationError):
         field.clean(value)
コード例 #5
0
ファイル: forms.py プロジェクト: williemwewa/cadasta-platform
class ProjectEditDetails(SanitizeFieldsForm, forms.ModelForm):
    urls = pg_forms.SimpleArrayField(
        forms.URLField(required=False),
        required=False,
        error_messages={'item_invalid': ""},
    )
    questionnaire = forms.CharField(required=False,
                                    widget=S3FileUploadWidget(
                                        upload_to='xls-forms',
                                        accepted_types=QUESTIONNAIRE_TYPES))
    original_file = forms.CharField(required=False,
                                    max_length=200,
                                    widget=forms.HiddenInput)
    access = org_fields.PublicPrivateField()
    contacts = org_fields.ContactsField(form=ContactsForm, required=False)

    class Media:
        js = ('js/file-upload.js', 'js/sanitize.js')

    class Meta:
        model = Project
        fields = [
            'name', 'description', 'access', 'urls', 'questionnaire',
            'contacts'
        ]

    def clean_questionnaire(self):
        new_form = self.data.get('questionnaire')
        current_form = self.initial.get('questionnaire')

        if (new_form is not None and new_form != current_form
                and self.instance.has_records):
            raise ValidationError(
                _("Data has already been contributed to this project. To "
                  "ensure data integrity, uploading a new questionnaire is "
                  "disabled for this project."))

    def save(self, *args, **kwargs):
        new_form = self.data.get('questionnaire')
        original_file = self.data.get('original_file')
        current_form = self.initial.get('questionnaire')

        if new_form:
            if current_form != new_form:
                Questionnaire.objects.create_from_form(
                    xls_form=new_form,
                    original_file=original_file,
                    project=self.instance)
        elif new_form is not None and not self.instance.has_records:
            self.instance.current_questionnaire = ''

        return super().save(*args, **kwargs)

    def clean_name(self):
        name = self.cleaned_data['name']

        # Check that name is not restricted
        invalid_names = settings.CADASTA_INVALID_ENTITY_NAMES
        if slugify(name, allow_unicode=True) in invalid_names:
            raise forms.ValidationError(
                _("Project name cannot be “Add” or “New”."))

        # Check that name is unique org-wide
        # (Explicit validation because we are using a wizard and the
        # unique_together validation cannot occur in the proper page)
        not_unique = Project.objects.filter(name__iexact=name).exclude(
            id=self.instance.id).exists()
        if not_unique:
            raise forms.ValidationError(
                _("Project with this name already exists"))

        return name
コード例 #6
0
 def test_widget_attr(self):
     field = org_fields.ContactsField(form=ContactsForm)
     widget_attrs = field.widget_attrs('widget')
     assert widget_attrs == {'formset': field.formset}
コード例 #7
0
 def test_init(self):
     field = org_fields.ContactsField(form=ContactsForm)
     assert isinstance(field.formset, type(formset_factory(ContactsForm)))