Python django.forms 模块,Form() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.forms.Form()

项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean(self):
        # clean()???? ??? ???? dict? ???
        # cleaned_data = super().clean()
        # username, password? ??? ????? ??
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        # username, password? ??? ??? authenticate
        user = authenticate(
            username=username,
            password=password
        )
        # ??? ??? ??, Form? cleaned_data? 'user'
        # ?? ??? User??? ??
        if user is not None:
            self.cleaned_data['user'] = user
        # ??? ??? ??, is_valid()? ???? ????
        # ValidationError? ????
        else:
            raise forms.ValidationError(
                'Login credentials not valid'
            )
        return self.cleaned_data
项目:csv_generator    作者:fatboystring    | 项目源码 | 文件源码
def _construct_form(self, i, **kwargs):
        """
        Construct form method
        Backwards compatible to django 1.7

        :param i: Form index
        :type i: int

        :param kwargs: Default form kwargs
        :type kwargs: {}

        :return: Form instance
        """
        kwargs.update({'csv_generator': self.instance})
        return super(CsvGeneratorColumnFormSet, self)._construct_form(
            i, **kwargs
        )
项目:django-formtools-addons    作者:vikingco    | 项目源码 | 文件源码
def test_get_context_data_inheritance(self):
        class TestWizard(CookieWizardView):
            """
            A subclass that implements ``get_context_data`` using the standard
            protocol for generic views (accept only **kwargs).

            See ticket #17148.
            """
            def get_context_data(self, **kwargs):
                context = super(TestWizard, self).get_context_data(**kwargs)
                context['test_key'] = 'test_value'
                return context

        factory = RequestFactory()
        view = TestWizard.as_view([forms.Form])

        response = view(factory.get('/'))
        self.assertEqual(response.context_data['test_key'], 'test_value')
项目:directory-ui-buyer    作者:uktrade    | 项目源码 | 文件源码
def test_templates_render_successfully():

    template_list = []
    template_dirs = [
        os.path.join(settings.BASE_DIR, 'enrolment/templates'),
        os.path.join(settings.BASE_DIR, 'supplier/templates'),
    ]
    for template_dir in template_dirs:
        for dir, dirnames, filenames in os.walk(template_dir):
            for filename in filenames:
                path = os.path.join(dir, filename).replace(template_dir, '')
                template_list.append(path.lstrip('/'))

    default_context = {
        'supplier': None,
        'form': Form(),
    }
    assert template_list
    for template in template_list:
        render_to_string(template, default_context)
项目:stoicism    作者:srgpdbd    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        extra_field = kwargs.pop('extra')
        # create dict appropriate for MultipleChoiceField
        # like {question: [[option:option]]}
        extra_fields = {}
        for key in extra_field.keys():
            options = []
            # unpack QuerySet
            for answer_option in extra_field[key]:
                options.append((answer_option.option, answer_option.option))
            extra_fields[key] = options
        super(forms.Form, self).__init__(*args, **kwargs)
        for i, question in enumerate(extra_fields.keys()):
            # add answer options to fields
            self.fields['question_%s' % i] = forms.MultipleChoiceField(
                label=question,
                widget=forms.CheckboxSelectMultiple,
                choices=extra_fields[question]
                )
项目:deb-python-django-formtools    作者:openstack    | 项目源码 | 文件源码
def test_get_context_data_inheritance(self):
        class TestWizard(CookieWizardView):
            """
            A subclass that implements ``get_context_data`` using the standard
            protocol for generic views (accept only **kwargs).

            See ticket #17148.
            """
            def get_context_data(self, **kwargs):
                context = super(TestWizard, self).get_context_data(**kwargs)
                context['test_key'] = 'test_value'
                return context

        factory = RequestFactory()
        view = TestWizard.as_view([forms.Form])

        response = view(factory.get('/'))
        self.assertEqual(response.context_data['test_key'], 'test_value')
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(GeneralFSForm, self).__init__(*args, **kwargs)
        if hasattr(self.request, "project") and self.request.project is not None:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True) |
                Q(fieldsightformlibrary__project=self.request.project) |
                Q(fieldsightformlibrary__organization=self.request.organization))

        elif hasattr(self.request, "organization") and self.request.organization is not None:
            xform = XForm.objects.filter(
                Q(user=self.request.user) |
                Q(fieldsightformlibrary__is_global=True) |
                Q(fieldsightformlibrary__organization=self.request.organization))
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True))
        self.fields['xf'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['xf'].empty_label = None
        self.fields['xf'].label = "Form"
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(GeneralForm, self).__init__(*args, **kwargs)
        # if hasattr(self.request, "project") and self.request.project is not None:
        #     xform = XForm.objects.filter(
        #         Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True) |
        #         Q(fieldsightformlibrary__project=self.request.project) |
        #         Q(fieldsightformlibrary__organization=self.request.organization))

        if hasattr(self.request, "organization") and self.request.organization is not None:
            xform = XForm.objects.filter(
                Q(user=self.request.user) |
                Q(user__userprofile__organization=self.request.organization))
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True))
        self.fields['xf'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['xf'].empty_label = None
        self.fields['xf'].label = "Form"
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(KoScheduleForm, self).__init__(*args, **kwargs)
        # if hasattr(self.request, "project") and self.request.project is not None:
        #     xform = XForm.objects.filter(
        #         Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True) |
        #         Q(fieldsightformlibrary__project=self.request.project) |
        #         Q(fieldsightformlibrary__organization=self.request.organization))

        if hasattr(self.request, "organization") and self.request.organization is not None:
            xform = XForm.objects.filter(
                Q(user=self.request.user) |
                Q(user__userprofile__organization=self.request.organization))
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True))
        self.fields['form'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['form'].empty_label = None
        self.fields['form'].label = "Select Form"
项目:fermentrack    作者:thorrak    | 项目源码 | 文件源码
def set_choices(self, family):
        # There's probably a better way of doing this
        board_choices = [(brd.id, brd.name) for brd in Board.objects.filter(family=family)]

        self.fields['board_type'].choices = board_choices


# class GuidedDeviceFlashForm(forms.Form):
#     DEVICE_FAMILY_CHOICES = GuidedDeviceSelectForm.DEVICE_FAMILY_CHOICES
#
#     device_family = forms.ChoiceField(label="Device Family",
#                                       widget=forms.Select(attrs={'class': 'form-control',
#                                                                  'data-toggle': 'select'}),
#                                       choices=DEVICE_FAMILY_CHOICES, required=True)
#     should_flash_device = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False)
#
#
项目:django-postgres-composite-types    作者:danni    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._bound_fields_cache = {}

        initial = self.form.initial.get(self.name, self.field.initial)
        if isinstance(initial, CompositeType):
            initial = initial.__to_dict__()

        if self.form.is_bound:
            data = self.form.data
        else:
            data = None

        self.composite_form = forms.Form(
            data=data, initial=initial, prefix=self.form.add_prefix(self.name))
        self.composite_form.fields = copy.deepcopy(self.field.fields)
项目:borgcube    作者:enkore    | 项目源码 | 文件源码
def process_docstring(app, what, name, form: forms.Form, options, lines):
    if not isinstance(form, type):
        return lines
    if not issubclass(form, forms.Form):
        return lines

    for name, field in form.declared_fields.items():
        lines.append('`{name}` = `{mod}.{qn}`'.format(
            # Django docs has these aliased, hence forms.fields -> forms.
            name=name, mod=field.__class__.__module__.replace('forms.fields', 'forms'), qn=field.__class__.__qualname__))
        lines.append('')

    del form.declared_fields
    del form.base_fields
    del form.media

    return lines
项目:borgcube    作者:enkore    | 项目源码 | 文件源码
def edit_view(self, request):
        client = self.client
        data = request.POST or None
        client.connection._p_activate()
        client_form = Client.Form(data, initial=client.__dict__)
        del client_form.fields['hostname']
        connection_form = RshClientConnection.Form(data, initial=client.connection.__dict__)
        if data and client_form.is_valid() and connection_form.is_valid():
            client._update(client_form.cleaned_data)
            client.connection._update(connection_form.cleaned_data)
            transaction.get().note('Edited client %s' % client.hostname)
            transaction.commit()
            return self.redirect_to()
        return self.render(request, 'core/client/edit.html', {
            'client': client,
            'client_form': client_form,
            'connection_form': connection_form,
        })
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def make_accept_invite_form(invitation):
    class AcceptInviteForm(forms.Form):
        if invitation.as_ringer:
            attending_character = forms.ModelChoiceField(
                queryset=invitation.invited_player.character_set,
                 empty_label="NPC only",
                 help_text="Instead of one of your characters, you will play an NPC",
                 required=False,
                 disabled=True)
        else:
            queryset = ""
            users_living_character_ids = [char.id for char in invitation.invited_player.character_set.all() if not char.is_dead()]
            required_status = invitation.relevant_game.required_character_status
            if required_status == HIGH_ROLLER_STATUS[0][0]:
                queryset = Character.objects.filter(id__in=users_living_character_ids)
            else:
                queryset = Character.objects.filter(id__in=users_living_character_ids).filter(status=invitation.relevant_game.required_character_status)
            attending_character = forms.ModelChoiceField(queryset=queryset,
                                                         empty_label=None,
                                                         help_text="Declare which character you're attending with. Private "
                                                                   "Characters and their powers will be revealed to the "
                                                                   "Game creator if selected.",
                                                         required=True)
    return AcceptInviteForm
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def make_drawback_form(drawback):
    class DrawbackForm(forms.Form):
        def get_label(drawback):
            requirements = ""
            required_status = {}
            for status in HIGH_ROLLER_STATUS: required_status[status[0]] = status[1]
            if drawback.required_status in [HIGH_ROLLER_STATUS[2][0], HIGH_ROLLER_STATUS[3][0]]:
                requirements = "requires: {}".format(required_status[drawback.required_status])
            return '{} ({}) {}'.format(drawback.name, drawback.description, requirements)

        label= get_label(drawback)
        eratta = drawback.eratta
        drawback_slug=str(drawback.slug)
        multiplicity_allowed=drawback.multiplicity_allowed;
        is_selected = forms.BooleanField(required=True)
        set_field_html_name(is_selected, drawback.form_name())
        if drawback.detail_field_label is not "" and drawback.detail_field_label is not None:
            detail_text = forms.CharField(required=False,
                                          label=drawback.detail_field_label)
            set_field_html_name(detail_text, drawback.form_detail_name())

    return DrawbackForm
项目:stardust-rpg    作者:johnthagen    | 项目源码 | 文件源码
def done(self, form_list: Sequence[forms.Form], form_dict: Dict[str, forms.Form],
             character_id: str, shop_id: str, **kwargs) -> HttpResponse:
        character = get_object_or_404(Character, pk=character_id)
        shop = get_object_or_404(Shop, pk=shop_id)

        if self.request.user.is_superuser:
            inventory_slot_form, item_form = self.get_forms(form_dict)
            new_shop_slot = ShopSlot(
                shop=shop,
                slot=inventory_slot_form.cleaned_data['slot'],
                quantity=inventory_slot_form.cleaned_data['quantity'],
                item_index=item_form.cleaned_data['item_enum'].value)
            new_shop_slot.save()
        else:
            messages.error(self.request, 'User not authorized to edit this shop.')
        return redirect(reverse(shops, args=[character.id, shop.id]))
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def handle(self, form):
        """
        Handle method
        Sends an email to the specified recipients

        :param form: Valid form instance
        :type form: django.forms.Form
        """
        message = EmailMessage(
            self.subject,
            self._render_template(form.cleaned_data),
            settings.DEFAULT_FROM_EMAIL,
            self.recipients.split(',')
        )

        for file_object in self.get_files(form):
            message.attach(file_object.name, file_object.read(), file_object.content_type)

        message.send()
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def handle(self, form):
        """
        Handle method
        Saves object instance to the database

        :param form: Valid form instance
        :type form: django.forms.Form
        """
        try:
            save_instance = import_string('django.forms.models.save_instance')
            commit = True

            if form.instance.pk is None:
                fail_message = 'created'
            else:
                fail_message = 'changed'

            save_instance(
                form, form.instance, form._meta.fields,
                fail_message, commit, form._meta.exclude,
                construct=False
            )
        except (ImportError, AttributeError):  # Django > 1.8
            form.instance.save()
            form._save_m2m()
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def test_get_context_data_inheritance(self):
        class TestWizard(CookieWizardView):
            """
            A subclass that implements ``get_context_data`` using the standard
            protocol for generic views (accept only **kwargs).

            See ticket #17148.
            """
            def get_context_data(self, **kwargs):
                context = super(TestWizard, self).get_context_data(**kwargs)
                context['test_key'] = 'test_value'
                return context

        factory = RequestFactory()
        view = TestWizard.as_view([forms.Form])

        response = view(factory.get('/'))
        self.assertEqual(response.context_data['test_key'], 'test_value')
项目:netbox    作者:digitalocean    | 项目源码 | 文件源码
def __init__(self, query_key, query_url, field_to_update, obj_label=None, *args, **kwargs):

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

        self.attrs = {
            'data-key': query_key,
            'data-source': reverse_lazy(query_url),
            'data-field': field_to_update,
        }

        if obj_label:
            self.attrs['data-label'] = obj_label


#
# Form fields
#
项目:mes    作者:osess    | 项目源码 | 文件源码
def test_context_pollution(self):
        class ExampleForm(forms.Form):
            comment = forms.CharField()

        form = ExampleForm()
        form2 = TestForm()

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {{ form.as_ul }}
            {% crispy form2 %}
            {{ form.as_ul }}
        """)
        c = Context({'form': form, 'form2': form2})
        html = template.render(c)

        self.assertEqual(html.count('name="comment"'), 2)
        self.assertEqual(html.count('name="is_company"'), 1)
项目:maas    作者:maas    | 项目源码 | 文件源码
def test_DictCharField_honors_field_constraint(self):
        class FakeForm(forms.Form):
            multi_field = DictCharField(
                [
                    ('field_a', forms.CharField(label='Field a')),
                    ('field_b', forms.CharField(
                        label='Field b', required=False, max_length=3)),
                ])

        # Create a value that will fail validation because it's too long.
        fielda_value = factory.make_string(10)
        data = QueryDict('multi_field_field_b=%s' % fielda_value)
        form = FakeForm(data)

        self.assertFalse(form.is_valid())
        self.assertEqual(
            {'multi_field': [
                'Field a: This field is required.',
                'Field b: Ensure this value has at '
                'most 3 characters (it has 10).']},
            form.errors)
项目:maas    作者:maas    | 项目源码 | 文件源码
def test_DictCharField_skip_check_true_skips_validation(self):
        # Create a value that will fail validation because it's too long.
        field_name = factory.make_string(10)
        field_value = factory.make_string(10)
        # multi_field_skip_check=true will make the form accept the value
        # even if it's not valid.
        data = QueryDict(
            'multi_field_%s=%s&multi_field_skip_check=true' % (
                field_name, field_value))

        class FakeFormSkip(forms.Form):
            multi_field = DictCharField(
                [(field_name, forms.CharField(label='Unused', max_length=3))],
                skip_check=True)
        form = FakeFormSkip(data)

        self.assertTrue(form.is_valid())
        self.assertEqual(
            {field_name: field_value},
            form.cleaned_data['multi_field'])
项目:maas    作者:maas    | 项目源码 | 文件源码
def test_DictCharField_skip_check_false(self):
        # Create a value that will fail validation because it's too long.
        field_value = factory.make_string(10)
        field_name = factory.make_string()
        field_label = factory.make_string()
        # Force the check with multi_field_skip_check=false.
        data = QueryDict(
            'multi_field_%s=%s&multi_field_skip_check=false' % (
                field_name, field_value))

        class FakeFormSkip(forms.Form):
            multi_field = DictCharField(
                [(field_name, forms.CharField(
                    label=field_label, max_length=3))],
                skip_check=True)
        form = FakeFormSkip(data)

        self.assertFalse(form.is_valid())
        self.assertEqual(
            {
                'multi_field': [
                    "%s: Ensure this value has at most 3 characters "
                    "(it has 10)." % field_label]
            },
            form.errors)
项目:maas    作者:maas    | 项目源码 | 文件源码
def test_DictCharField_accepts_required_false(self):
        # A form where the DictCharField instance is constructed with
        # required=False.
        class FakeFormRequiredFalse(forms.Form):
            multi_field = DictCharField(
                [('field_a', forms.CharField(label='Field a'))],
                required=False)
            char_field = forms.CharField(label='Field a')

        char_value = factory.make_string(10)
        data = QueryDict('char_field=%s' % (char_value))
        form = FakeFormRequiredFalse(data)
        self.assertTrue(form.is_valid())
        self.assertEqual(
            {'char_field': char_value, 'multi_field': None},
            form.cleaned_data)
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def __init__(self, tenant, request, initial=None):
        self.user = request.user
        self.tenant = tenant
        self.all_orgs = Organization.objects.get_for_user(request.user, scope=REQUIRED_SCOPE)
        org_choices = [(six.text_type(x.id), x.name) for x in self.all_orgs]
        if request.method == 'POST':
            forms.Form.__init__(self, request.POST)
        else:
            forms.Form.__init__(self, initial)
        self.fields['orgs'].choices = org_choices
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def __init__(self, tenant, request, initial=None):
        self.tenant = tenant
        project_choices = []
        self.projects_by_id = {}

        for org in tenant.organizations.all():
            teams = Team.objects.get_for_user(
                org, tenant.auth_user, scope=REQUIRED_SCOPE, with_projects=True
            )
            for team, projects in teams:
                for project in projects:
                    project_choices.append(
                        (
                            six.text_type(project.id),
                            '%s | %s / %s' % (org.name, team.name, project.name)
                        )
                    )
                    self.projects_by_id[six.text_type(project.id)] = project

        project_choices.sort(key=lambda x: x[1].lower())

        if request.method == 'POST':
            forms.Form.__init__(self, request.POST, initial)
        else:
            forms.Form.__init__(self, initial)

        self.fields['projects'].choices = project_choices
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_populate(self):
        """Create a FormsetDataTable and populate it with data."""

        class TableForm(forms.Form):
            name = forms.CharField()
            value = forms.IntegerField()

        TableFormset = forms.formsets.formset_factory(TableForm, extra=0)

        class Table(table_formset.FormsetDataTable):
            formset_class = TableFormset

            name = tables.Column('name')
            value = tables.Column('value')

            class Meta(object):
                name = 'table'

        table = Table(self.request)
        table.data = TEST_DATA_4
        formset = table.get_formset()
        self.assertEqual(2, len(formset))
        form = formset[0]
        form_data = form.initial
        self.assertEqual('object_1', form_data['name'])
        self.assertEqual(2, form_data['value'])
项目:django-ajax-views    作者:Pyco7    | 项目源码 | 文件源码
def helper(self):
        """
        The :class:`DefaultFormHelper` is instantiated only once when this helper property is accessed first.

        Assign your own form helper if you want to override the default behavior.

        This renders hidden fields and appends form actions by default.

        :return: Form helper instance
        """
        if self._helper_instance is not None:
            return self._helper_instance
        if self.form_cfg:
            self.fields['form_cfg'] = CharField(widget=HiddenInput(), required=False)
            self.fields['form_cfg'].initial = json.dumps(self.form_cfg)
        try:
            self.init_add_fields()
        except AttributeError:
            pass
        helper = DefaultFormHelper(self)
        if 'form_action' in self.opts:
            helper.form_action = self.opts['form_action']
        helper.render_hidden_fields = True
        helper.append_form_actions()
        self._helper_instance = helper
        return helper
项目:django-ajax-views    作者:Pyco7    | 项目源码 | 文件源码
def render_form_actions(self):
        form = Form()
        form.opts = self.opts
        form.helper = DefaultFormHelper(self)
        form.helper.add_form_actions_only()
        return render_crispy_form(form)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __init__(self, form, field, readonly_fields=None, model_admin=None):
        self.form = form  # A django.forms.Form instance
        if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
            self.fields = [field]
        else:
            self.fields = field
        self.has_visible_field = not all(field in self.form.fields and
                                         self.form.fields[field].widget.is_hidden
                                         for field in self.fields)
        self.model_admin = model_admin
        if readonly_fields is None:
            readonly_fields = ()
        self.readonly_fields = readonly_fields
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __init__(self, form, field, readonly_fields=None, model_admin=None):
        self.form = form  # A django.forms.Form instance
        if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
            self.fields = [field]
        else:
            self.fields = field
        self.has_visible_field = not all(
            field in self.form.fields and self.form.fields[field].widget.is_hidden
            for field in self.fields
        )
        self.model_admin = model_admin
        if readonly_fields is None:
            readonly_fields = ()
        self.readonly_fields = readonly_fields
项目:zing    作者:evernote    | 项目源码 | 文件源码
def test_form_multistringformfield(value):
    """Tests `MultiStringFormField`'s value compression in a form."""
    def test_form_factory(nplurals):
        class TestForm(Form):
            value = MultiStringFormField(nplurals=nplurals)

        return TestForm

    data = {'value_%d' % i: val for i, val in enumerate(value)}
    form_class = test_form_factory(nplurals=len(value))
    form = form_class(data=data)
    assert form.is_valid()
    assert form.cleaned_data == {'value': value}
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def make_reorder_languagelist_form(objlist):
    choices = [(e.id, e.ascii_name) for e in objlist]

    class ReorderLanguageListForm(forms.Form):
        language = forms.ChoiceField(
            choices=choices,
            widget=forms.Select(attrs={"size": 20}))
    return ReorderLanguageListForm
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def make_reorder_meaninglist_form(objlist):
    choices = [(e.id, e.gloss) for e in objlist]

    class ReorderMeaningListForm(forms.Form):
        meaning = forms.ChoiceField(
            choices=choices,
            widget=forms.Select(attrs={"size": 20}))
    return ReorderMeaningListForm
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def get_widget_params_form(self, wizard):
        data = wizard.get_cleaned_data_for_step(wizard.steps.first)
        widget_type = data['widget_type']
        widget = widget_manager.get(widget_type)
        fields = copy.deepcopy(widget.base_fields)
        if 'id' in fields:
            del fields['id']
        return DeclarativeFieldsMetaclass("WidgetParamsForm", (forms.Form,), fields)
项目:django-echoices    作者:mbourqui    | 项目源码 | 文件源码
def test_form(self):
        # SEE: https://docs.djangoproject.com/en/stable/ref/forms/api/#using-forms-to-validate-data
        class SimpleForm(forms.Form):
            choice = make_echoicefield(ETestCharChoices).formfield()

        f = SimpleForm(dict(choice=ETestCharChoices.FIELD1))
        self.assertTrue(f.is_valid())

        f = SimpleForm(dict(choice=ETestCharChoices.FIELD1.value))
        self.assertTrue(f.is_valid())

        f = SimpleForm(dict(choice=''))
        self.assertFalse(f.is_valid())
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def __init__(self, form, field, readonly_fields=None, model_admin=None):
        self.form = form  # A django.forms.Form instance
        if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
            self.fields = [field]
        else:
            self.fields = field
        self.has_visible_field = not all(
            field in self.form.fields and self.form.fields[field].widget.is_hidden
            for field in self.fields
        )
        self.model_admin = model_admin
        if readonly_fields is None:
            readonly_fields = ()
        self.readonly_fields = readonly_fields
项目:csv_generator    作者:fatboystring    | 项目源码 | 文件源码
def test_extends_form(self):
        """
        The form should extend django.forms.Form
        """
        self.assertTrue(issubclass(SelectCsvGeneratorForm, forms.Form))
项目:csv_generator    作者:fatboystring    | 项目源码 | 文件源码
def get_form_kwargs(self, index):
        """
        Adds the csv_generator instance to the form kwargs

        :param index: Form index
        :type index: int

        :return: Dict for form kwargs
        """
        kwargs = super(CsvGeneratorColumnFormSet, self).get_form_kwargs(index)
        kwargs.update({'csv_generator': self.instance})
        return kwargs
项目:csv_generator    作者:fatboystring    | 项目源码 | 文件源码
def empty_form(self):
        """
        Constructs an empty form for the formset
        Backwards compatible to django 1.7

        :return: Form instance
        """
        form = self.form(
            auto_id=self.auto_id,
            prefix=self.add_prefix('__prefix__'),
            empty_permitted=True,
            csv_generator=self.instance
        )
        self.add_fields(form, None)
        return form
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
def get_widget_params_form(self, wizard):
        data = wizard.get_cleaned_data_for_step(wizard.steps.first)
        widget_type = data['widget_type']
        widget = widget_manager.get(widget_type)
        fields = copy.deepcopy(widget.base_fields)
        if 'id' in fields:
            del fields['id']
        return DeclarativeFieldsMetaclass("WidgetParamsForm", (forms.Form,), fields)