django.forms.ModelForm - python examples

Here are the examples of the python api django.forms.ModelForm taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

51 Examples 7

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_model_first_field(self):
        """
        Regression for ensuring ModelAdmin.field can handle first elem being a
        non-model field (test fix for UnboundLocalError introduced with r16225).
        """
        clast SongForm(forms.ModelForm):
            extra_data = forms.CharField()

            clast Meta:
                model = Song
                fields = '__all__'

        clast FieldsOnFormOnlyAdmin(admin.ModelAdmin):
            form = SongForm
            fields = ['extra_data', 'satle']

        errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_form_validation(self):
        # If a form is specified, it should use it allowing custom validation
        # to work properly. This won't break any of the admin widgets or media.
        clast AdminBandForm(forms.ModelForm):
            delete = forms.BooleanField()

        clast BandAdmin(ModelAdmin):
            form = AdminBandForm

        ma = BandAdmin(Band, self.site)
        self.astertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date', 'delete'])
        self.astertEqual(type(ma.get_form(request).base_fields['sign_date'].widget), AdminDateWidget)

3 View Complete Implementation : test_forms.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_save_new_uses_form_save(self):
        clast SaveTestForm(forms.ModelForm):
            def save(self, *args, **kwargs):
                self.instance.saved_by = 'custom method'
                return super().save(*args, **kwargs)

        Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', form=SaveTestForm)
        instance = ProxyRelatedModel.objects.create()
        data = {
            'form-TOTAL_FORMS': '1',
            'form-INITIAL_FORMS': '0',
            'form-MAX_NUM_FORMS': '',
            'form-0-satle': 'foo',
        }
        formset = Formset(data, instance=instance, prefix='form')
        self.astertTrue(formset.is_valid())
        new_obj = formset.save()[0]
        self.astertEqual(new_obj.saved_by, 'custom method')

3 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_update_get_object(self):
        res = self.client.get('/edit/author/update/')
        self.astertEqual(res.status_code, 200)
        self.astertIsInstance(res.context['form'], forms.ModelForm)
        self.astertIsInstance(res.context['view'], View)
        self.astertEqual(res.context['object'], self.author)
        self.astertEqual(res.context['author'], self.author)
        self.astertTemplateUsed(res, 'generic_views/author_form.html')

        # Modification with both POST and PUT (browser compatible)
        res = self.client.post('/edit/author/update/', {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
        self.astertEqual(res.status_code, 302)
        self.astertRedirects(res, '/list/authors/')
        self.astertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_disabled_modelchoicefield(self):
        clast ModelChoiceForm(forms.ModelForm):
            author = forms.ModelChoiceField(Author.objects.all(), disabled=True)

            clast Meta:
                model = Book
                fields = ['author']

        book = Book.objects.create(author=Writer.objects.create(name='Test writer'))
        form = ModelChoiceForm({}, instance=book)
        self.astertEqual(
            form.errors['author'],
            ['Select a valid choice. That choice is not one of the available choices.']
        )

3 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_create(self):
        res = self.client.get('/edit/authors/create/')
        self.astertEqual(res.status_code, 200)
        self.astertIsInstance(res.context['form'], forms.ModelForm)
        self.astertIsInstance(res.context['view'], View)
        self.astertNotIn('object', res.context)
        self.astertNotIn('author', res.context)
        self.astertTemplateUsed(res, 'generic_views/author_form.html')

        res = self.client.post('/edit/authors/create/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
        self.astertEqual(res.status_code, 302)
        self.astertRedirects(res, '/list/authors/')
        self.astertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_label_for_field_form_argument(self):
        clast ArticleForm(forms.ModelForm):
            extra_form_field = forms.BooleanField()

            clast Meta:
                fields = '__all__'
                model = Article

        self.astertEqual(
            label_for_field('extra_form_field', Article, form=ArticleForm()),
            'Extra form field'
        )
        msg = "Unable to lookup 'nonexistent' on Article or ArticleForm"
        with self.astertRaisesMessage(AttributeError, msg):
            label_for_field('nonexistent', Article, form=ArticleForm()),

3 View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_valid_case(self):
        clast AdminBandForm(forms.ModelForm):
            delete = forms.BooleanField()

        clast BandAdmin(ModelAdmin):
            form = AdminBandForm
            fieldsets = (
                ('Band', {
                    'fields': ('name', 'bio', 'sign_date', 'delete')
                }),
            )

        self.astertIsValid(BandAdmin, Band)

3 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_update_get_object(self):
        a = Author.objects.create(
            pk=1,
            name='Randall Munroe',
            slug='randall-munroe',
        )
        res = self.client.get('/edit/author/update/')
        self.astertEqual(res.status_code, 200)
        self.astertIsInstance(res.context['form'], forms.ModelForm)
        self.astertIsInstance(res.context['view'], View)
        self.astertEqual(res.context['object'], Author.objects.get(pk=a.pk))
        self.astertEqual(res.context['author'], Author.objects.get(pk=a.pk))
        self.astertTemplateUsed(res, 'generic_views/author_form.html')

        # Modification with both POST and PUT (browser compatible)
        res = self.client.post('/edit/author/update/', {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
        self.astertEqual(res.status_code, 302)
        self.astertRedirects(res, '/list/authors/')
        self.astertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_model_fields(self):
        """
        Regression for ensuring ModelAdmin.fields can contain non-model fields
        that broke with r11737
        """
        clast SongForm(forms.ModelForm):
            extra_data = forms.CharField()

        clast FieldsOnFormOnlyAdmin(admin.ModelAdmin):
            form = SongForm
            fields = ['satle', 'extra_data']

        errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_update_post(self):
        res = self.client.get('/edit/author/%d/update/' % self.author.pk)
        self.astertEqual(res.status_code, 200)
        self.astertIsInstance(res.context['form'], forms.ModelForm)
        self.astertEqual(res.context['object'], self.author)
        self.astertEqual(res.context['author'], self.author)
        self.astertTemplateUsed(res, 'generic_views/author_form.html')
        self.astertEqual(res.context['view'].get_form_called_count, 1)

        # Modification with both POST and PUT (browser compatible)
        res = self.client.post(
            '/edit/author/%d/update/' % self.author.pk,
            {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}
        )
        self.astertEqual(res.status_code, 302)
        self.astertRedirects(res, '/list/authors/')
        self.astertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_inherited_unique_field_with_form(self):
        """
        A model which has different primary key for the parent model pastes
        unique field checking correctly (#17615).
        """
        clast ProfileForm(forms.ModelForm):
            clast Meta:
                model = Profile
                fields = '__all__'

        User.objects.create(username="user_only")
        p = Profile.objects.create(username="user_with_profile")
        form = ProfileForm({'username': "user_with_profile", 'extra': "hello"}, instance=p)
        self.astertTrue(form.is_valid())

3 View Complete Implementation : admin.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def __init__(self, *args, **kwargs):
    # this was initially written to be used for any BaseContent, that's
    # why we don't astume the content_type to be pre-determined
    # TODO(nicoechaniz): update code
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        if self.instance.id is not None:
            instance_type = ContentType.objects.get_for_model(self.instance)
            selected_items = [
                values[0] for values in
                MenuItem.objects.filter(
                    content_type=instance_type,
                    object_id=self.instance.id).values_list('id') ]
            self.fields['menu_items'].initial = selected_items

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def _get_model_form_clast(model_form_clast, model_container, admin, request):
    if not model_form_clast:
        form_kwargs = dict(
            form=forms.ModelForm,
            fields=forms.ALL_FIELDS,
        )

        if admin and request:
            form_kwargs['formfield_callback'] = functools.partial(
                admin.formfield_for_dbfield, request=request)

        model_form_clast = modelform_factory(model_container, **form_kwargs)

    return model_form_clast

3 View Complete Implementation : test_product_forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def get_dummy_form(self, **kwargs):
        clast DummyForm(forms.ModelForm):
            clast Meta:
                model = AttributeValue
                exclude = []

            def __init__(self, *args, **kwargs):
                self.cleaned_data = kwargs.pop('cleaned_data')
                self.cleaned_data['DELETE'] = False
                super(DummyForm, self).__init__(*args, **kwargs)
        return DummyForm(**kwargs)

3 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
    def test_tag_field_in_modelform(self):
        # Ensure that automatically created forms use TagField
        clast TestForm(forms.ModelForm):
            clast Meta:
                model = FormTest
                
        form = TestForm()
        self.astertEquals(form.fields['tags'].__clast__.__name__, 'TagField')

3 View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_splitarraywidget_value_omitted_from_data(self):
        clast Form(forms.ModelForm):
            field = SplitArrayField(forms.IntegerField(), required=False, size=2)

            clast Meta:
                model = IntegerArrayModel
                fields = ('field',)

        form = Form({'field_0': '1', 'field_1': '2'})
        self.astertEqual(form.errors, {})
        obj = form.save(commit=False)
        self.astertEqual(obj.field, [1, 2])

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_formfield_override_readonly(self):
        clast AdminBandForm(forms.ModelForm):
            name = forms.CharField()

            clast Meta:
                exclude = ()
                model = Band

        clast BandAdmin(ModelAdmin):
            form = AdminBandForm
            readonly_fields = ['name']

        ma = BandAdmin(Band, self.site)

        # `name` shouldn't appear in base_fields because it's part of
        # readonly_fields.
        self.astertEqual(
            list(ma.get_form(request).base_fields),
            ['bio', 'sign_date']
        )
        # But it should appear in get_fields()/fieldsets() so it can be
        # displayed as read-only.
        self.astertEqual(
            list(ma.get_fields(request)),
            ['bio', 'sign_date', 'name']
        )
        self.astertEqual(
            list(ma.get_fieldsets(request)),
            [(None, {'fields': ['bio', 'sign_date', 'name']})]
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_form_meta_exclude(self):
        """
        The custom ModelForm's `Meta.exclude` is overridden if
        `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined (#14496).
        """
        # With ModelAdmin
        clast AdminBandForm(forms.ModelForm):
            clast Meta:
                model = Band
                exclude = ['bio']

        clast BandAdmin(ModelAdmin):
            exclude = ['name']
            form = AdminBandForm

        ma = BandAdmin(Band, self.site)
        self.astertEqual(list(ma.get_form(request).base_fields), ['bio', 'sign_date'])

        # With InlineModelAdmin
        clast AdminConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                exclude = ['day']

        clast ConcertInline(TabularInline):
            exclude = ['transport']
            form = AdminConcertForm
            fk_name = 'main_band'
            model = Concert

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        ma = BandAdmin(Band, self.site)
        self.astertEqual(
            list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
            ['main_band', 'opening_band', 'day', 'id', 'DELETE']
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_form_exclude_kwarg_override(self):
        """
        The `exclude` kwarg pasted to `ModelAdmin.get_form()` overrides all
        other declarations (#8999).
        """
        clast AdminBandForm(forms.ModelForm):
            clast Meta:
                model = Band
                exclude = ['name']

        clast BandAdmin(ModelAdmin):
            exclude = ['sign_date']
            form = AdminBandForm

            def get_form(self, request, obj=None, **kwargs):
                kwargs['exclude'] = ['bio']
                return super().get_form(request, obj, **kwargs)

        ma = BandAdmin(Band, self.site)
        self.astertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date'])

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_overriding_get_exclude_with_form_fields(self):
        clast AdminConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                fields = ['main_band', 'opening_band', 'day', 'transport']

        clast ConcertInline(TabularInline):
            form = AdminConcertForm
            fk_name = 'main_band'
            model = Concert

            def get_exclude(self, request, obj=None):
                return ['opening_band']

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        ma = BandAdmin(Band, self.site)
        self.astertEqual(
            list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
            ['main_band', 'day', 'transport', 'id', 'DELETE']
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_overriding_get_exclude_with_form_exclude(self):
        clast AdminConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                exclude = ['day']

        clast ConcertInline(TabularInline):
            form = AdminConcertForm
            fk_name = 'main_band'
            model = Concert

            def get_exclude(self, request, obj=None):
                return ['opening_band']

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        ma = BandAdmin(Band, self.site)
        self.astertEqual(
            list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
            ['main_band', 'day', 'transport', 'id', 'DELETE']
        )

0 View Complete Implementation : wizard.py
Copyright Apache License 2.0
Author : BeanWei
    def get_step_form(self, step=None):
        if step is None:
            step = self.steps.current
        attrs = self.get_form_list()[step]
        if type(attrs) in (list, tuple):
            return modelform_factory(self.model, form=forms.ModelForm,
                                     fields=attrs, formfield_callback=self.admin_view.formfield_for_dbfield)
        elif type(attrs) is dict:
            if attrs.get('fields', None):
                return modelform_factory(self.model, form=forms.ModelForm,
                                         fields=attrs['fields'], formfield_callback=self.admin_view.formfield_for_dbfield)
            if attrs.get('callback', None):
                callback = attrs['callback']
                if callable(callback):
                    return callback(self)
                elif hasattr(self.admin_view, str(callback)):
                    return getattr(self.admin_view, str(callback))(self)
        elif issubclast(attrs, forms.BaseForm):
            return attrs
        return None

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_queryset_override(self):
        # If the queryset of a ModelChoiceField in a custom form is overridden,
        # RelatedFieldWidgetWrapper doesn't mess that up.
        band2 = Band.objects.create(name='The Beatles', bio='', sign_date=date(1962, 1, 1))

        ma = ModelAdmin(Concert, self.site)
        form = ma.get_form(request)()

        self.astertHTMLEqual(
            str(form["main_band"]),
            '<div clast="related-widget-wrapper">'
            '<select name="main_band" id="id_main_band" required>'
            '<option value="" selected>---------</option>'
            '<option value="%d">The Beatles</option>'
            '<option value="%d">The Doors</option>'
            '</select></div>' % (band2.id, self.band.id)
        )

        clast AdminConcertForm(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.fields["main_band"].queryset = Band.objects.filter(name='The Doors')

        clast ConcertAdminWithForm(ModelAdmin):
            form = AdminConcertForm

        ma = ConcertAdminWithForm(Concert, self.site)
        form = ma.get_form(request)()

        self.astertHTMLEqual(
            str(form["main_band"]),
            '<div clast="related-widget-wrapper">'
            '<select name="main_band" id="id_main_band" required>'
            '<option value="" selected>---------</option>'
            '<option value="%d">The Doors</option>'
            '</select></div>' % self.band.id
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_foreign_key_as_radio_field(self):
        # Now specify all the fields as radio_fields.  Widgets should now be
        # RadioSelect, and the choices list should have a first entry of 'None' if
        # blank=True for the model field.  Finally, the widget should have the
        # 'radiolist' attr, and 'inline' as well if the field is specified HORIZONTAL.
        clast ConcertAdmin(ModelAdmin):
            radio_fields = {
                'main_band': HORIZONTAL,
                'opening_band': VERTICAL,
                'day': VERTICAL,
                'transport': HORIZONTAL,
            }

        cma = ConcertAdmin(Concert, self.site)
        cmafa = cma.get_form(request)

        self.astertEqual(type(cmafa.base_fields['main_band'].widget.widget), AdminRadioSelect)
        self.astertEqual(cmafa.base_fields['main_band'].widget.attrs, {'clast': 'radiolist inline'})
        self.astertEqual(
            list(cmafa.base_fields['main_band'].widget.choices),
            [(self.band.id, 'The Doors')]
        )

        self.astertEqual(type(cmafa.base_fields['opening_band'].widget.widget), AdminRadioSelect)
        self.astertEqual(cmafa.base_fields['opening_band'].widget.attrs, {'clast': 'radiolist'})
        self.astertEqual(
            list(cmafa.base_fields['opening_band'].widget.choices),
            [('', 'None'), (self.band.id, 'The Doors')]
        )
        self.astertEqual(type(cmafa.base_fields['day'].widget), AdminRadioSelect)
        self.astertEqual(cmafa.base_fields['day'].widget.attrs, {'clast': 'radiolist'})
        self.astertEqual(list(cmafa.base_fields['day'].widget.choices), [(1, 'Fri'), (2, 'Sat')])

        self.astertEqual(type(cmafa.base_fields['transport'].widget), AdminRadioSelect)
        self.astertEqual(cmafa.base_fields['transport'].widget.attrs, {'clast': 'radiolist inline'})
        self.astertEqual(
            list(cmafa.base_fields['transport'].widget.choices),
            [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]
        )

        clast AdminConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                exclude = ('transport',)

        clast ConcertAdmin(ModelAdmin):
            form = AdminConcertForm

        ma = ConcertAdmin(Concert, self.site)
        self.astertEqual(list(ma.get_form(request).base_fields), ['main_band', 'opening_band', 'day'])

        clast AdminConcertForm(forms.ModelForm):
            extra = forms.CharField()

            clast Meta:
                model = Concert
                fields = ['extra', 'transport']

        clast ConcertAdmin(ModelAdmin):
            form = AdminConcertForm

        ma = ConcertAdmin(Concert, self.site)
        self.astertEqual(list(ma.get_form(request).base_fields), ['extra', 'transport'])

        clast ConcertInline(TabularInline):
            form = AdminConcertForm
            model = Concert
            fk_name = 'main_band'
            can_delete = True

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        ma = BandAdmin(Band, self.site)
        self.astertEqual(
            list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
            ['extra', 'transport', 'id', 'DELETE', 'main_band']
        )

0 View Complete Implementation : test_product_forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def test_clean(self):
        formset_factory = inlineformset_factory(
            Attribute,
            AttributeChoice,
            formset=AttributeChoiceInlineFormSet,
            exclude=[],
        )
        formset = formset_factory()

        clast DummyForm(forms.ModelForm):
            clast Meta:
                model = AttributeChoice
                exclude = []

            def __init__(self, *args, **kwargs):
                self.cleaned_data = kwargs.pop('cleaned_data')
                self.cleaned_data['DELETE'] = False
                super(DummyForm, self).__init__(*args, **kwargs)

        form1 = DummyForm(cleaned_data={'value': 1})
        form2 = DummyForm(cleaned_data={'value': 1})  # duplicate
        formset.forms = []
        self.astertRaises(ValidationError, formset.clean)  # no forms
        formset.forms = [form1, form2]
        self.astertRaises(ValidationError, formset.clean)  # duplicate values
        formset.forms = [form1]
        self.astertIsNone(formset.clean())  # past through
        formset.instance = None
        self.astertIsNone(formset.clean())  # no instance

0 View Complete Implementation : test_cms_plugins_blogpost.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_blogpost_form_page_choices(self):
        """
        The form to create a blogpost plugin should only list blogpost pages
        in the select box.
        """

        clast BlogPostPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = BlogPostPluginModel
                fields = ["page"]

        blog_page = create_i18n_page("my satle", published=True)
        blogpost = BlogPostFactory(page_parent=blog_page)
        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = BlogPostPluginModelForm()
        rendered_form = plugin_form.as_table()
        self.astertEqual(rendered_form.count(blogpost.extended_object.get_satle()), 1)
        self.astertNotIn(other_page_satle, plugin_form.as_table())

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_form_meta_exclude_with_readonly(self):
        """
        The custom ModelForm's `Meta.exclude` is respected when used in
        conjunction with `ModelAdmin.readonly_fields` and when no
        `ModelAdmin.exclude` is defined (#14496).
        """
        # With ModelAdmin
        clast AdminBandForm(forms.ModelForm):
            clast Meta:
                model = Band
                exclude = ['bio']

        clast BandAdmin(ModelAdmin):
            readonly_fields = ['name']
            form = AdminBandForm

        ma = BandAdmin(Band, self.site)
        self.astertEqual(list(ma.get_form(request).base_fields), ['sign_date'])

        # With InlineModelAdmin
        clast AdminConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                exclude = ['day']

        clast ConcertInline(TabularInline):
            readonly_fields = ['transport']
            form = AdminConcertForm
            fk_name = 'main_band'
            model = Concert

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        ma = BandAdmin(Band, self.site)
        self.astertEqual(
            list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
            ['main_band', 'opening_band', 'id', 'DELETE'])

0 View Complete Implementation : test_cms_plugins_category.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_category_form_page_choices_all_categories(self):
        """
        By default, all categories can be linked via a plugin excluding meta categories.
        There shouldn't be any duplicate because of published status.
        """

        clast CategoryPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = CategoryPluginModel
                fields = ["page"]

        meta_category = CategoryFactory(should_publish=True)
        parent_category = CategoryFactory(
            page_parent=meta_category.extended_object, should_publish=True
        )
        leaf_category = CategoryFactory(
            page_parent=parent_category.extended_object, should_publish=True
        )

        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )

        plugin_form = CategoryPluginModelForm()
        rendered_form = plugin_form.as_table()

        self.astertEqual(
            rendered_form.count(leaf_category.extended_object.get_satle()), 1
        )
        self.astertEqual(
            rendered_form.count(parent_category.extended_object.get_satle()), 1
        )
        self.astertNotIn(meta_category.extended_object.get_satle(), rendered_form)
        self.astertNotIn(other_page_satle, rendered_form)

0 View Complete Implementation : test_cms_plugins_course.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_course_form_page_choices(self):
        """
        The form to create a course plugin should only list course pages
        in the select box and no snapshot. There shouldn't be any duplicate because
        of published status.
        """

        clast CoursePluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = CoursePluginModel
                fields = ["page"]

        page = create_i18n_page("A page")
        page.publish("en")
        course = CourseFactory(page_parent=page, should_publish=True)
        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = CoursePluginModelForm()
        rendered_form = plugin_form.as_table()
        self.astertEqual(rendered_form.count(course.extended_object.get_satle()), 1)
        self.astertNotIn(other_page_satle, plugin_form.as_table())

        # Create a fake course snapshot and make sure it's not available to select
        snapshot = CourseFactory(
            page_parent=course.extended_object, should_publish=True
        )
        self.astertNotIn(snapshot.extended_object.get_satle(), plugin_form.as_table())

0 View Complete Implementation : permissions.py
Copyright GNU General Public License v3.0
Author : evernote
def admin_permissions(request, current_directory, template, ctx):
    language = ctx.get('language', None)

    negative_permissions_excl = list(PERMISSIONS['negative'])
    positive_permissions_excl = list(PERMISSIONS['positive'])

    # Don't provide means to alter access permissions under /<lang_code>/*
    # In other words: only allow setting access permissions for the root
    # and the `/projects/<code>/` directories
    if language is not None:
        access_permissions = ['view', 'hide']
        negative_permissions_excl.extend(access_permissions)
        positive_permissions_excl.extend(access_permissions)

    content_type = get_permission_contenttype()

    positive_permissions_qs = content_type.permission_set.exclude(
        codename__in=negative_permissions_excl,
    )
    negative_permissions_qs = content_type.permission_set.exclude(
        codename__in=positive_permissions_excl,
    )

    base_queryset = User.objects.filter(is_active=1).exclude(
        id__in=current_directory.permission_sets.values_list('user_id',
                                                             flat=True),)
    choice_groups = [(None, base_queryset.filter(
        username__in=('nobody', 'default')
    ))]

    choice_groups.append((
        _('All Users'),
        base_queryset.exclude(username__in=('nobody',
                                            'default')).order_by('username'),
    ))

    clast PermissionSetForm(forms.ModelForm):

        clast Meta(object):
            model = PermissionSet
            fields = ('user', 'directory', 'positive_permissions',
                      'negative_permissions')

        directory = forms.ModelChoiceField(
            queryset=Directory.objects.filter(pk=current_directory.pk),
            initial=current_directory.pk,
            widget=forms.HiddenInput,
        )
        user = GroupedModelChoiceField(
            label=_('Username'),
            choice_groups=choice_groups,
            queryset=User.objects.all(),
            required=True,
            widget=forms.Select(attrs={
                'clast': 'js-select2 select2-username',
            }),
        )
        positive_permissions = PermissionFormField(
            label=_('Add Permissions'),
            queryset=positive_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(attrs={
                'clast': 'js-select2 select2-multiple',
                'data-placeholder': _('Select one or more permissions'),
            }),
        )
        negative_permissions = PermissionFormField(
            label=_('Revoke Permissions'),
            queryset=negative_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(attrs={
                'clast': 'js-select2 select2-multiple',
                'data-placeholder': _('Select one or more permissions'),
            }),
        )

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

            # Don't display extra negative permissions field where they
            # are not applicable
            if language is not None:
                del self.fields['negative_permissions']

    link = lambda instance: unicode(instance.user)
    directory_permissions = current_directory.permission_sets \
                                             .order_by('user').all()

    return util.edit(request, template, PermissionSet, ctx, link,
                     linkfield='user', queryset=directory_permissions,
                     can_delete=True, form=PermissionSetForm)

0 View Complete Implementation : test_cms_plugins_organization.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_organization_form_page_choices(self):
        """
        The form to create a organization plugin should only list organization pages
        in the select box. There shouldn't be any duplicate because of published status.
        """

        clast OrganizationPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = OrganizationPluginModel
                fields = ["page"]

        organization = OrganizationFactory(should_publish=True)
        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = OrganizationPluginModelForm()
        rendered_form = plugin_form.as_table()
        self.astertEqual(
            rendered_form.count(organization.extended_object.get_satle()), 1
        )
        self.astertNotIn(other_page_satle, plugin_form.as_table())

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_exclude_kwarg_override(self):
        """
        The `exclude` kwarg pasted to `InlineModelAdmin.get_formset()`
        overrides all other declarations (#8999).
        """
        clast AdminConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                exclude = ['day']

        clast ConcertInline(TabularInline):
            exclude = ['transport']
            form = AdminConcertForm
            fk_name = 'main_band'
            model = Concert

            def get_formset(self, request, obj=None, **kwargs):
                kwargs['exclude'] = ['opening_band']
                return super().get_formset(request, obj, **kwargs)

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        ma = BandAdmin(Band, self.site)
        self.astertEqual(
            list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
            ['main_band', 'day', 'transport', 'id', 'DELETE']
        )

0 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
def generate_translation_form(translatable):
    r"""
    Return the `Translation` form based on a `Translatable` model and
    the `translation language`\ s.
    """
    fields = translatable._get_translatable_fields_choices()
    languages = _get_translation_choices()

    clast TranslationForm(forms.ModelForm):
        field = forms.ChoiceField(choices=fields)
        language = forms.ChoiceField(choices=languages)

        clast Meta:
            model = Translation
            fields = (
                'field',
                'language',
                'text',
            )

    return TranslationForm

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_regression_for_ticket_15820(self):
        """
        `obj` is pasted from `InlineModelAdmin.get_fieldsets()` to
        `InlineModelAdmin.get_formset()`.
        """
        clast CustomConcertForm(forms.ModelForm):
            clast Meta:
                model = Concert
                fields = ['day']

        clast ConcertInline(TabularInline):
            model = Concert
            fk_name = 'main_band'

            def get_formset(self, request, obj=None, **kwargs):
                if obj:
                    kwargs['form'] = CustomConcertForm
                return super().get_formset(request, obj, **kwargs)

        clast BandAdmin(ModelAdmin):
            inlines = [ConcertInline]

        Concert.objects.create(main_band=self.band, opening_band=self.band, day=1)
        ma = BandAdmin(Band, self.site)
        inline_instances = ma.get_inline_instances(request)
        fieldsets = list(inline_instances[0].get_fieldsets(request))
        self.astertEqual(fieldsets[0][1]['fields'], ['main_band', 'opening_band', 'day', 'transport'])
        fieldsets = list(inline_instances[0].get_fieldsets(request, inline_instances[0].model))
        self.astertEqual(fieldsets[0][1]['fields'], ['day'])

0 View Complete Implementation : admin.py
Copyright GNU General Public License v3.0
Author : CodigoSur
def media_admin_factory(media_model):
    clast MediaLibraryForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(MediaLibraryForm, self).__init__(*args, **kwargs)
            author_choices = [('', '------')]
            for author in Author.objects.all():
                if media_model in [ctype.model_clast()
                                   for ctype in author.content_types.all()]:
                    author_choices.append((author.id, author.name))
            self.fields['author'].choices = author_choices

        def save(self, *args, **kwargs):
            # We override the standard behavior because we've overriden the FileBrowseField
            # with a simple ClearableFileInput
            if self.simple:
                abs_paths = {}
                instance = super(MediaLibraryForm, self).save(commit=False)
                image_file_field = instance.image_file_field

                file_fields = [ instance.media_file_field ]
                if image_file_field:
                    file_fields.append(image_file_field)
                for f_field in file_fields:
                    folder = media_model._meta.get_field_by_name(f_field)[0].directory
                    abs_paths[f_field] = os.path.join( 
                        settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, folder
                    )
                    if f_field in self.files.keys():
                        f = self.files[f_field]
                        f.name = convert_filename(f.name)
                        name = handle_file_upload(abs_paths[f_field], f)
                        setattr(instance, f_field, name)
                    else:
                        # TODO(nicoechaniz): this is ugly! refactor
                        if f_field in ["image", "still"]:
                            if hasattr(self, "image_file_initial"):
                                setattr(instance, f_field, self.image_file_initial)
                        else:
                            if hasattr(self, "media_file_initial"):
                                setattr(instance, f_field, self.media_file_initial)
                instance.save()
                return instance
            else:
                return super(MediaLibraryForm, self).save(*args, **kwargs)

        clast Meta:
            model = media_model

    if media_model in has_thumbnail:
        list_display = ['name', 'published', 'thumbnail']
    else:
        list_display = ['name', 'published']
    list_display += CollectibleAdmin.list_display

    return type('%sAdmin' % media_model.__name__,
                (MediaAdmin,),
                {'form': MediaLibraryForm, 'list_display': list_display})

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_disabled_multiplemodelchoicefield(self):
        clast ArticleForm(forms.ModelForm):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)

            clast Meta:
                model = Article
                fields = ['categories']

        category1 = Category.objects.create(name='cat1')
        category2 = Category.objects.create(name='cat2')
        article = Article.objects.create(
            pub_date=datetime.date(1988, 1, 4),
            writer=Writer.objects.create(name='Test writer'),
        )
        article.categories.set([category1.pk])

        form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
        self.astertEqual(form.errors, {})
        self.astertEqual([x.pk for x in form.cleaned_data['categories']], [category2.pk])
        # Disabled fields use the value from `instance` rather than `data`.
        form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
        form.fields['categories'].disabled = True
        self.astertEqual(form.errors, {})
        self.astertEqual([x.pk for x in form.cleaned_data['categories']], [category1.pk])

0 View Complete Implementation : test_cms_plugins_person.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_person_form_page_choices(self):
        """
        The form to create a person plugin should only list person pages in the select box.
        """

        clast PersonPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = PersonPluginModel
                fields = ["page"]

        person = PersonFactory()
        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = PersonPluginModelForm()
        self.astertIn(person.extended_object.get_satle(), plugin_form.as_table())
        self.astertNotIn(other_page_satle, plugin_form.as_table())

0 View Complete Implementation : test_cms_plugins_category.py
Copyright MIT License
Author : openfun
    @override_settings(LIMIT_PLUGIN_CATEGORIES_TO_LEAF=True)
    def test_cms_plugins_category_form_page_choices_leaf_only(self):
        """
        The form to create a category plugin should only list leaf category pages in the
        select box when the setting is activated. There shouldn't be any duplicate because
        of published status.
        """

        clast CategoryPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = CategoryPluginModel
                fields = ["page"]

        meta_category = CategoryFactory(should_publish=True)
        parent_category = CategoryFactory(
            page_parent=meta_category.extended_object, should_publish=True
        )
        leaf_category = CategoryFactory(
            page_parent=parent_category.extended_object, should_publish=True
        )

        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )

        plugin_form = CategoryPluginModelForm()
        rendered_form = plugin_form.as_table()

        self.astertEqual(
            rendered_form.count(leaf_category.extended_object.get_satle()), 1
        )
        self.astertNotIn(parent_category.extended_object.get_satle(), rendered_form)
        self.astertNotIn(meta_category.extended_object.get_satle(), rendered_form)
        self.astertNotIn(other_page_satle, rendered_form)

0 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
    def get_form(self, step=None, data=None, files=None):
        """
        Constructs the form for a given `step`. If no `step` is defined, the
        current step will be determined automatically.

        The form will be initialized using the `data` argument to prefill the
        new form. If needed, instance or queryset (for `ModelForm` or
        `ModelFormSet`) will be added too.
        """
        if step is None:
            step = self.steps.current
        # prepare the kwargs for the form instance.
        kwargs = self.get_form_kwargs(step)
        kwargs.update({
            'data': data,
            'files': files,
            'prefix': self.get_form_prefix(step, self.form_list[step]),
            'initial': self.get_form_initial(step),
        })
        if issubclast(self.form_list[step], forms.ModelForm):
            # If the form is based on ModelForm, add instance if available
            # and not previously set.
            kwargs.setdefault('instance', self.get_form_instance(step))
        elif issubclast(self.form_list[step], forms.models.BaseModelFormSet):
            # If the form is based on ModelFormSet, add queryset if available
            # and not previous set.
            kwargs.setdefault('queryset', self.get_form_instance(step))
        return self.form_list[step](**kwargs)

0 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : evernote
def unit_comment_form_factory(language):

    comment_attrs = {
        'lang': language.code,
        'dir': language.direction,
        'clast': 'comments expanding focusthis',
        'rows': 1,
        'tabindex': 15,
    }

    clast UnitCommentForm(forms.ModelForm):

        clast Meta(object):
            fields = ('translator_comment',)
            model = Unit

        translator_comment = forms.CharField(
            required=True,
            label=_("Translator comment"),
            widget=forms.Textarea(attrs=comment_attrs),
        )

        def __init__(self, *args, **kwargs):
            self.request = kwargs.pop('request', None)
            self.previous_value = ''

            super(UnitCommentForm, self).__init__(*args, **kwargs)

            if self.request.method == 'DELETE':
                self.fields['translator_comment'].required = False

        def clean_translator_comment(self):
            # HACKISH: Setting empty string when `DELETE` is being used
            if self.request.method == 'DELETE':
                self.previous_value = self.instance.translator_comment
                return ''

            return self.cleaned_data['translator_comment']

        def save(self, **kwargs):
            """Register the submission and save the comment."""
            if self.has_changed():
                self.instance._comment_updated = True
                creation_time = timezone.now()
                translation_project = self.request.translation_project

                sub = Submission(
                    creation_time=creation_time,
                    translation_project=translation_project,
                    submitter=self.request.user,
                    unit=self.instance,
                    store=self.instance.store,
                    field=SubmissionFields.COMMENT,
                    type=SubmissionTypes.NORMAL,
                    old_value=self.previous_value,
                    new_value=self.cleaned_data['translator_comment']
                )
                sub.save()

            super(UnitCommentForm, self).save(**kwargs)

    return UnitCommentForm

0 View Complete Implementation : test_cms_plugins_program.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_program_form_page_choices(self):
        """
        The form to create a program plugin should only list program pages
        in the select box.
        """

        clast ProgramPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = ProgramPluginModel
                fields = ["page"]

        program_page = create_i18n_page("my satle", published=True)
        program = ProgramFactory(page_parent=program_page)
        other_page_satle = "other page"
        create_page(
            other_page_satle, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = ProgramPluginModelForm()
        rendered_form = plugin_form.as_table()
        self.astertEqual(rendered_form.count(program.extended_object.get_satle()), 1)
        self.astertNotIn(other_page_satle, plugin_form.as_table())

0 View Complete Implementation : views_landing.py
Copyright GNU General Public License v3.0
Author : GovReady
@login_required
def new_org_group(request):
    # Create new organization group

    clast NewOrgForm(forms.ModelForm):
        clast Meta:
            model = Organization
            fields = ['name', 'slug']
            labels = {
                "name": "Group name",
                "slug": "Group \"slug\" to appear in URLs",
            }
            help_texts = {
                "name": "An organizational group for you teams astessments.",
                "slug": "Only lowercase letters, digits, and dashes.",
            }
            widgets = {
                "name": forms.TextInput(attrs={"placeholder": "Privacy Office"}),
                "slug": forms.TextInput(attrs={"placeholder": "privacy"})
            }

        def clean_slug(self):
            # Not sure why the field validator isn't being run by the ModelForm.
            import re
            from .models import subdomain_regex
            from django.forms import ValidationError
            if not re.match(subdomain_regex, self.cleaned_data['slug']):
                raise ValidationError("The organization address must contain only lowercase letters, digits, and dashes and cannot start or end with a dash.")
            return self.cleaned_data['slug']

    neworg_form = NewOrgForm()

    if request.POST.get("action") == "neworg":
        # signup_form = SignupForm(request.POST)
        neworg_form = NewOrgForm(request.POST)
        if request.user.is_authenticated and neworg_form.is_valid():
            # Perform new org group creation, then redirect
            # to that org group.
            with transaction.atomic():
                if not request.user.is_authenticated:
                    # TODO Log message that usunloged in user tried to create a group
                    return HttpResponseRedirect("/")
                else:
                    user = request.user
                org = Organization.create(admin_user=user, **neworg_form.cleaned_data)
                return HttpResponseRedirect("/" + org.slug + "/projects")

    return render(request, "org_groups/new_org_group.html", {
        "neworg_form": neworg_form,
        # "member_of_orgs": Organization.get_all_readable_by(request.user) if request.user.is_authenticated else None,
    })

0 View Complete Implementation : forms.py
Copyright MIT License
Author : hugobessa
def get_tenant_specific_table_row_form_clast(table_name):

    table_id = TenantSpecificTable.objects.get(name=table_name).id
    tenant_specific_fields_definitions = TenantSpecificFieldDefinition.objects.filter(
        table_content_type=ContentType.objects.get_for_model(TenantSpecificTable),
        table_id=table_id
    )
    tenant_specific_fields_names = list(tenant_specific_fields_definitions.values_list('name', flat=True))

    clast TenantSpecificTableRowForm(forms.ModelForm):

        clast Meta:
            model = TenantSpecificTableRow
            fields = ['id']

        form_tenant_specific_field_mapping = {
            'integer': forms.IntegerField,
            'char': forms.CharField,
            'text': forms.CharField,
            'float': forms.FloatField,
            'datetime': forms.DateTimeField,
            'date': forms.DateField,
        }

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

            for definition in tenant_specific_fields_definitions:
                if not self.fields.get(definition.name, False):
                    field_kwargs = {}
                    if definition.is_required:
                        field_kwargs.update({
                            'required': True,
                            'allow_null': True
                        })
                    if definition.default_value is not None:
                        field_kwargs.update(
                            {'initial': definition.default_value})

                    self.fields[definition.name] = \
                        self.form_tenant_specific_field_mapping[definition.data_type](
                            **field_kwargs)

        def full_clean(self):
            """
            Clean all of self.data and populate self._errors and self.cleaned_data.
            """
            from django.forms.utils import ErrorDict
            self._errors = ErrorDict()
            if not self.is_bound:  # Stop further processing.
                return
            self.cleaned_data = {'table_id': table_id}
            # If the form is permitted to be empty, and none of the form data has
            # changed from the initial data, short circuit any validation.
            if self.empty_permitted and not self.has_changed():
                return

            self._clean_fields()
            self._clean_tenant_specific_fields()
            self._clean_form()
            self._post_clean()

        def _clean_tenant_specific_fields(self):
            for name, field in self.fields.items():
                if name in tenant_specific_fields_names:
                    definition = tenant_specific_fields_definitions.get(name=name)
                    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
                    try:
                        value = field.clean(value)
                        validators = []
                        for validator_instance in definition.validators.all():
                            validator_function = import_from_string(validator_instance.module_path)
                            validators.append(validator_function)

                        validate_method = compose_list(validators)
                        self.cleaned_data[name] = validate_method(value)
                        if hasattr(self, 'clean_%s' % name):
                            value = getattr(self, 'clean_%s' % name)()
                            self.cleaned_data[name] = value
                    except ValidationError as e:
                        self.add_error(name, e)

        def save(self, *args, **kwargs):
            self.instance.table_id = table_id
            new_instance = super(TenantSpecificTableRowForm, self).save(*args, **kwargs)
            return get_custom_table_manager(table_name).get(id=new_instance.id)

        def _post_clean(self):
            super(TenantSpecificTableRowForm, self)._post_clean()
            for name, value in [(k, v) for k, v in self.cleaned_data.items() if k in tenant_specific_fields_names]:
                setattr(self.instance, name, value)

    return TenantSpecificTableRowForm

0 View Complete Implementation : test_cms_plugins_organizations_by_category.py
Copyright MIT License
Author : openfun
    def test_cms_plugins_organizations_by_category_form_page_choices(self):
        """
        The form to create an organizations by category plugin should only list category pages
        in the select box. There shouldn't be any duplicate because of published status.
        """

        clast OrganizationsByCategoryPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            clast Meta:
                model = OrganizationsByCategoryPluginModel
                fields = ["page"]

        category = CategoryFactory(should_publish=True)
        PageFactory(satle__satle="other page", should_publish=True)

        plugin_form = OrganizationsByCategoryPluginModelForm()
        rendered_form = plugin_form.as_table()

        self.astertEqual(rendered_form.count(category.extended_object.get_satle()), 1)
        self.astertNotIn("other", plugin_form.as_table())

0 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : evernote
def unit_form_factory(language, snplurals=None, request=None):

    if snplurals is not None:
        tnplurals = language.nplurals
    else:
        tnplurals = 1

    action_disabled = False
    if request is not None:
        cantranslate = check_permission("translate", request)
        cansuggest = check_permission("suggest", request)

        if not (cansuggest or cantranslate):
            action_disabled = True

    target_attrs = {
        'lang': language.code,
        'dir': language.direction,
        'clast': 'translation expanding focusthis js-translation-area',
        'rows': 2,
        'tabindex': 10,
    }

    fuzzy_attrs = {
        'accesskey': 'f',
        'clast': 'fuzzycheck',
        'tabindex': 13,
    }

    if action_disabled:
        target_attrs['disabled'] = 'disabled'
        fuzzy_attrs['disabled'] = 'disabled'

    clast UnitForm(forms.ModelForm):
        clast Meta(object):
            model = Unit
            fields = ('target_f', 'state',)

        target_f = MultiStringFormField(
            nplurals=tnplurals,
            required=False,
            attrs=target_attrs,
        )
        state = UnitStateField(
            required=False,
            label=_('Needs work'),
            widget=forms.CheckboxInput(
                attrs=fuzzy_attrs,
                check_test=lambda x: x == FUZZY,
            ),
        )
        similarity = forms.FloatField(required=False)
        mt_similarity = forms.FloatField(required=False)
        suggestion = forms.ModelChoiceField(
            queryset=Suggestion.objects.all(),
            required=False)
        comment = forms.CharField(required=False)

        def __init__(self, *args, **kwargs):
            self.request = kwargs.pop('request', None)
            super(UnitForm, self).__init__(*args, **kwargs)
            self._updated_fields = []

            self.fields['target_f'].widget.attrs['data-translation-aid'] = \
                self['target_f'].value()

        @property
        def updated_fields(self):
            order_dict = {
                SubmissionFields.STATE: 0,
                SubmissionFields.TARGET: 1,
            }
            return sorted(self._updated_fields, key=lambda x: order_dict[x[0]])

        def clean_target_f(self):
            value = self.cleaned_data['target_f']

            if self.instance.target != multistring(value or [u'']):
                self.instance._target_updated = True
                self._updated_fields.append((SubmissionFields.TARGET,
                                            to_db(self.instance.target),
                                            to_db(value)))

            return value

        def clean_similarity(self):
            value = self.cleaned_data['similarity']

            if 0 <= value <= 1 or value is None:
                return value

            raise forms.ValidationError(
                _('Value of `similarity` should be in in the [0..1] range')
            )

        def clean_mt_similarity(self):
            value = self.cleaned_data['mt_similarity']

            if 0 <= value <= 1 or value is None:
                return value

            raise forms.ValidationError(
                _('Value of `mt_similarity` should be in in the [0..1] range')
            )

        def clean(self):
            old_state = self.instance.state  # Integer
            is_fuzzy = self.cleaned_data['state']  # Boolean
            new_target = self.cleaned_data['target_f']

            # If suggestion is provided set `old_state` should be `TRANSLATED`.
            if self.cleaned_data['suggestion']:
                old_state = TRANSLATED

                # Skip `TARGET` field submission if suggestion value is equal
                # to submitted translation
                if new_target == self.cleaned_data['suggestion'].target_f:
                    self._updated_fields = []

            if (self.request is not None and
                not check_permission('administrate', self.request) and
                is_fuzzy):
                self.add_error('state',
                               forms.ValidationError(
                                   _('Needs work flag must be '
                                     'cleared')))

            if new_target:
                if old_state == UNTRANSLATED:
                    self.instance._save_action = TRANSLATION_ADDED
                    self.instance.store.mark_dirty(
                        CachedMethods.WORDCOUNT_STATS)
                else:
                    self.instance._save_action = TRANSLATION_CHANGED

                if is_fuzzy:
                    new_state = FUZZY
                else:
                    new_state = TRANSLATED
            else:
                new_state = UNTRANSLATED
                if old_state > FUZZY:
                    self.instance._save_action = TRANSLATION_DELETED
                    self.instance.store.mark_dirty(
                        CachedMethods.WORDCOUNT_STATS)

            if is_fuzzy != (old_state == FUZZY):
                # when Unit toggles its FUZZY state the number of translated
                # words also changes
                self.instance.store.mark_dirty(CachedMethods.WORDCOUNT_STATS,
                                               CachedMethods.LAST_ACTION)

            if old_state not in [new_state, OBSOLETE]:
                self.instance._state_updated = True
                self._updated_fields.append((SubmissionFields.STATE,
                                            old_state, new_state))

                self.cleaned_data['state'] = new_state
            else:
                self.instance._state_updated = False
                self.cleaned_data['state'] = old_state

            return super(UnitForm, self).clean()

    return UnitForm

0 View Complete Implementation : test_form_components.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_module_formset_required_for_publish(phase_factory):
    clast Form(forms.ModelForm):
        clast Meta:
            model = phase_models.Phase
            fields = ['start_date']
            required_for_project_publish = ['start_date']
            widgets = {'start_date': forms.TextInput()}

    FormSet = inlineformset_factory(module_models.Module,
                                    phase_models.Phase,
                                    form=Form,
                                    formset=ModuleDashboardFormSet,
                                    extra=0,
                                    can_delete=False,
                                    )

    phase = phase_factory(module__project__is_draft=True)
    module = phase.module
    project = module.project
    phase_factory(module=module)

    formset = FormSet(instance=module)
    astert formset.get_required_fields() == ['start_date']
    astert all(map(lambda field: field.required is False,
                   [form.fields['start_date'] for form in formset.forms]))

    project.is_draft = False
    formset = FormSet(instance=module)
    astert formset.get_required_fields() == ['start_date']
    astert all(map(lambda field: field.required is True,
                   [form.fields['start_date'] for form in formset.forms]))

0 View Complete Implementation : test_form_components.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_module_formset_component(phase_factory):
    clast Form(forms.ModelForm):
        clast Meta:
            model = phase_models.Phase
            fields = ['start_date']
            required_for_project_publish = ['start_date']
            widgets = {'start_date': forms.TextInput()}

    FormSet = inlineformset_factory(module_models.Module,
                                    phase_models.Phase,
                                    form=Form,
                                    formset=ModuleDashboardFormSet,
                                    extra=0,
                                    can_delete=False,
                                    )

    clast Component(ModuleFormSetComponent):
        identifier = 'test_id'
        weight = 1
        label = 'Module Settings'

        form_satle = 'Edit test module settings'
        form_clast = FormSet
        form_template_name = 'none'

    phase = phase_factory(module__project__is_draft=True,
                          start_date=None)
    module = phase.module
    phase_factory(module=module, start_date=None)

    component = Component()
    astert component.is_effective(module) is True

    urls = component.get_urls()
    astert len(urls) == 1
    regexp, _, name = urls[0]
    astert regexp == r'^modules/(?P<module_slug>[-\w_]+)/test_id/$'
    astert name == 'dashboard-test_id-edit'

    astert component.get_progress(module) == (0, 2)

    phase.start_date = now()
    phase.save()
    astert component.get_progress(module) == (1, 2)

0 View Complete Implementation : django.py
Copyright Mozilla Public License 2.0
Author : mozilla
def process_docstring(app, what, name, obj, options, lines):
    # Only look at objects that inherit from Django's base model clast
    if inspect.isclast(obj) and (
        issubclast(obj, models.Model) or issubclast(obj, forms.ModelForm)
    ):
        # Grab the field list from the meta clast
        fields = obj._meta.fields

        for field in fields:
            if isinstance(field, str):
                attname = field
                field = obj.base_fields[attname]
            else:
                attname = field.attname

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_text(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_text(
                getattr(field, "verbose_name", getattr(field, "label", field))
            ).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(":param %s: %s" % (attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(":param %s: %s" % (attname, verbose_name))

            # Add the field's type to the docstring
            if isinstance(field, models.ForeignKey):
                to = field.rel.to

                if isinstance(to, str):
                    module, name = to.split(".")
                else:
                    module, name = to.__module__, to.__name__
                lines.append(
                    ":type %s: %s to :clast:`~%s.%s`"
                    % (attname, type(field).__name__, module, name)
                )

            else:
                field_cls = type(field)
                module, name = field_cls.__module__, field_cls.__name__
                module = _field_module_map.get(module, module)
                lines.append(":type %s: :clast:`~%s.%s`" % (attname, module, name))

    # Return the extended docstring
    return lines

0 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_update_post(self):
        a = Author.objects.create(
            name='Randall Munroe',
            slug='randall-munroe',
        )
        res = self.client.get('/edit/author/%d/update/' % a.pk)
        self.astertEqual(res.status_code, 200)
        self.astertIsInstance(res.context['form'], forms.ModelForm)
        self.astertEqual(res.context['object'], Author.objects.get(pk=a.pk))
        self.astertEqual(res.context['author'], Author.objects.get(pk=a.pk))
        self.astertTemplateUsed(res, 'generic_views/author_form.html')
        self.astertEqual(res.context['view'].get_form_called_count, 1)

        # Modification with both POST and PUT (browser compatible)
        res = self.client.post(
            '/edit/author/%d/update/' % a.pk,
            {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}
        )
        self.astertEqual(res.status_code, 302)
        self.astertRedirects(res, '/list/authors/')
        self.astertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])