Python django.forms.Form() Examples

The following are 30 code examples for showing how to use django.forms.Form(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 6 votes vote down vote up
def make_config_form(self, data: Dict[str, Any] = None, files: Dict = None) -> BaseConfigForm:
        """
        Returns a Django Form instance that can be used to edit this question's details.

        The Form's 'cleaned_data' should match this QuestionVersion.config object (unless overriding this method and
        ConfigForm.to_jsonable to deal with differences)
        """
        if self.version is None:
            initial = {}
        else:
            initial = self.version.config

        if self.version.question:
            initial['points'] = self.question.points

        form = self.ConfigForm(data=data, files=files, initial=initial)
        if self.question.id:
            form.fields['points'].help_text = 'Changing this will update all versions of this question.'
        return form 
Example 2
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_entry_form(cls, editor, units, handler=None, person=None, **kwargs):
        """
        Return a Django Form that can be used to create/edit a CareerEvent
        """
        initial = {
            'start_date': datetime.date.today(),
        }
        form = cls.EntryForm(editor=editor,
                             units=units,
                             initial=initial,
                             handler=handler,
                             person=person,
                             **kwargs)
        form.legend = cls.NAME
        form.use_required_attribute = False
        return form

    # event configuration 
Example 3
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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" 
Example 4
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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__user_profile__organization=self.request.organization), deleted_xform=None)
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True), deleted_xform=None)
        self.fields['xf'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['xf'].empty_label = None
        self.fields['xf'].label = "Form"
        self.fields['default_submission_status'].choices = [(0, 'Pending'), (3, 'Approved'), ] 
Example 5
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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__user_profile__organization=self.request.organization), deleted_xform=None)
        else:
            xform = XForm.objects.filter(
                Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True), deleted_xform=None)
        self.fields['form'].choices = [(obj.id, obj.title) for obj in xform]
        self.fields['form'].empty_label = None
        self.fields['form'].label = "Select Form" 
Example 6
Project: anytask   Author: znick   File: forms.py    License: MIT License 6 votes vote down vote up
def __init__(self, course, *args, **kwargs):
        forms.Form.__init__(self, *args, **kwargs)

        self.groups = {}
        self.teachers = get_teacher_choises(course)
        groups_teacher = {}
        for default_teacher in DefaultTeacher.objects.filter(group__in=course.groups.all()):
            groups_teacher[default_teacher.group.id] = default_teacher.teacher.id

        for group in course.groups.all():
            group_key = "group_{0}".format(group.id)
            self.groups[group_key] = group
            self.fields[group_key] = forms.ChoiceField(
                initial=groups_teacher.get(group.id, 0),
                choices=self.teachers,
                label=group.name
            ) 
Example 7
Project: fermentrack   Author: thorrak   File: forms.py    License: MIT License 6 votes vote down vote up
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)
#
# 
Example 8
Project: sphinxcontrib-django   Author: edoburu   File: docstrings.py    License: Apache License 2.0 6 votes vote down vote up
def _add_form_fields(obj, lines):
    """Improve the documentation of a Django Form class.

    This highlights the available fields in the form.
    """
    lines.append("**Form fields:**")
    lines.append("")
    for name, field in obj.base_fields.items():
        field_type = "{}.{}".format(
            field.__class__.__module__, field.__class__.__name__
        )
        tpl = "* ``{name}``: {label} (:class:`~{field_type}`)"
        lines.append(
            tpl.format(
                name=name,
                field=field,
                label=field.label or name.replace("_", " ").title(),
                field_type=field_type,
            )
        ) 
Example 9
Project: django-polaris   Author: stellar   File: transactions.py    License: Apache License 2.0 6 votes vote down vote up
def after_form_validation(self, form: forms.Form, transaction: Transaction):
        """
        Use this function to process the data collected with `form` and to update
        the state of the interactive flow so that the next call to
        ``DepositIntegration.content_for_transaction`` returns a dictionary
        containing the next form to render to the user, or returns None.

        Keep in mind that if a ``TransactionForm`` is submitted, Polaris will
        update the `amount_in` and `amount_fee` with the information collected.
        There is no need to implement that yourself.

        DO NOT update `transaction.status` here or in any other function for
        that matter. This column is managed by Polaris and is expected to have
        particular values at different points in the flow.

        If you need to store some data to determine which form to return next when
        ``DepositIntegration.content_for_transaction`` is called, store this
        data in a model not used by Polaris.

        :param form: the completed ``forms.Form`` submitted by the user
        :param transaction: the ``Transaction`` database object
        """
        pass 
Example 10
Project: dissemin   Author: dissemin   File: test_protocol.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_bound_form(self, book_god_of_the_labyrinth, abstract_required, ddc, embargo, license_chooser):
        self.protocol.paper = book_god_of_the_labyrinth
        data = {
            'paper_pk' : book_god_of_the_labyrinth.pk
        }
        if abstract_required:
            data['abstract'] = 'Simple abstract'
        if ddc:
            data['ddc'] = ddc
        if license_chooser:
            data['license'] = license_chooser.pk
        if embargo == 'required':
            data['embargo'] = '2019-10-10'

        form = self.protocol.get_bound_form()
        if not form.is_valid():
            print(form.errors)
            raise AssertionError("Form not valid") 
Example 11
Project: pycon   Author: pythonitalia   File: test_mutations.py    License: MIT License 6 votes vote down vote up
def test_form_mutation_without_context():
    class TestForm(Form):
        a = IntegerField()

        def save(self, *args, **kwargs):
            return "hello"

    class TestMutation(FormMutation):
        class Meta:
            form_class = TestForm

    @strawberry.input
    class TestInput:
        a: int

    assert TestMutation.Mutation(None, TestInput(a=1)) == "hello" 
Example 12
Project: pycon   Author: pythonitalia   File: test_mutations.py    License: MIT License 6 votes vote down vote up
def test_form_mutation_response_can_be_converted_using_transform_method():
    class TestForm(Form):
        a = IntegerField()

        def save(self, *args, **kwargs):
            return "hello"

    class TestMutation(FormMutation):
        @classmethod
        def transform(cls, result):
            return "world"

        class Meta:
            form_class = TestForm

    @strawberry.input
    class TestInput:
        a: int

    assert TestMutation.Mutation(None, TestInput(a=1)) == "world" 
Example 13
Project: pycon   Author: pythonitalia   File: test_mutations.py    License: MIT License 6 votes vote down vote up
def test_form_mutation_transform_is_not_required():
    class TestForm(Form):
        a = IntegerField()

        def save(self, *args, **kwargs):
            return "hello"

    class TestMutation(FormMutation):
        class Meta:
            form_class = TestForm

    @strawberry.input
    class TestInput:
        a: int

    assert TestMutation.Mutation(None, TestInput(a=1)) == "hello" 
Example 14
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def done(self, form_list: List[Form], **kwargs: Any) -> HttpResponse:
        """
        Login the user and redirect to the desired page.

        We need to override this function so that we can redirect to
        realm.uri instead of '/'.
        """
        realm_uri = self.get_user().realm.uri
        # This mock.patch business is an unpleasant hack that we'd
        # ideally like to remove by instead patching the upstream
        # module to support better configurability of the
        # LOGIN_REDIRECT_URL setting.  But until then, it works.  We
        # import mock.patch here because mock has an expensive import
        # process involving pbr -> pkgresources (which is really slow).
        from unittest.mock import patch
        with patch.object(settings, 'LOGIN_REDIRECT_URL', realm_uri):
            return super().done(form_list, **kwargs) 
Example 15
Project: byro   Author: byro   File: members.py    License: Apache License 2.0 6 votes vote down vote up
def get_forms(self):
        """Instantiate forms, return a list of tuples like get_operations(), but with Form objects and expanded prefix values."""
        retval = []

        for prefix, title, form_class, buttons, callback in self.get_operations():
            retval.append(
                (
                    prefix,
                    title,
                    form_class(
                        prefix=prefix,
                        data=self.request.POST
                        if self.request.method == "POST"
                        else None,
                    ),
                    buttons,
                    callback,
                )
            )

        return retval 
Example 16
def errors_message(form):
        """Form Errors.

        :param form forms.Form
        form.errors.get_json_data() django 2.0 or higher

        :return
        example
        {
        "error": {
            "file": "This field is required.",
            "test": "This field is required."
            }
        }
        """
        data = form.errors.get_json_data()
        for k, v in data.items():
            data[k] = ' '.join([value_detail['message'] for value_detail in v])
        return data 
Example 17
Project: richie   Author: openfun   File: forms.py    License: MIT License 6 votes vote down vote up
def __init__(self, *args, data=None, **kwargs):
        """
        Adapt the search form to handle filters:
        - Fix the QueryDict value getter to properly handle multi-value parameters,
        - Add a field instance to the form for each filter,
        - Define the `states` property as it is used by several methods.
        """
        # QueryDict/MultiValueDict breaks lists: we need to fix it
        data_fixed = (
            {
                k: data.getlist(k)
                # Form fields are marked to expect lists as input or not as explained above
                if (k in FILTER_FIELDS and FILTER_FIELDS[k][1] is True) else v[0]
                for k, v in data.lists()
            }
            if data
            else {}
        )

        super().__init__(data=data_fixed, *args, **kwargs)
        self.fields.update({k: v[0] for k, v in FILTER_FIELDS.items()})
        self.states = None 
Example 18
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
def model_fields_form_factory(model):
    ''' Creates a form for specifying fields from a model to display. '''

    fields = model._meta.get_fields()

    choices = []
    for field in fields:
        if hasattr(field, "verbose_name"):
            choices.append((field.name, field.verbose_name))

    class ModelFieldsForm(forms.Form):
        fields = forms.MultipleChoiceField(
            choices=choices,
            required=False,
        )

    return ModelFieldsForm 
Example 19
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 20
Project: django-mysql   Author: adamchainz   File: test_forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_redisplay_wrong_input(self):
        """
        When displaying a bound form (typically due to invalid input), the form
        should not overquote JSONField inputs.
        """

        class JsonForm(forms.Form):
            name = forms.CharField(max_length=2)
            jfield = JSONField()

        # JSONField input is fine, name is too long
        form = JsonForm({"name": "xyz", "jfield": '["foo"]'})
        assert "[&quot;foo&quot;]</textarea>" in form.as_p()

        # This time, the JSONField input is wrong
        form = JsonForm({"name": "xy", "jfield": '{"foo"}'})
        # Appears once in the textarea and once in the error message
        assert form.as_p().count(escape('{"foo"}')) == 2 
Example 21
Project: Servo   Author: fpsw   File: queue.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def statuses(request, queue_id):
    """Lists available statuses for this queue"""
    queue = Queue.objects.get(pk=queue_id)
    
    class StatusForm(forms.Form):
        status = forms.ModelChoiceField(queryset=queue.queuestatus_set.all())

    form = StatusForm()
    return HttpResponse(str(form['status'])) 
Example 22
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            text_field = forms.CharField()
            date_field = forms.DateField()
        self.form_class = MockForm
        self.form = self.form_class() 
Example 23
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            enabled_field = forms.CharField()
            disabled_field = forms.CharField(
                widget=forms.TextInput(attrs={'disabled': True}))
        self.form_class = MockForm
        self.form = self.form_class() 
Example 24
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            writable_field = forms.CharField()
            readonly_field = forms.CharField(
                widget=forms.TextInput(attrs={'readonly': True}))
        self.form_class = MockForm
        self.form = self.form_class() 
Example 25
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # reorder the fields, so marking and review are last
        fields = self.fields
        assert isinstance(fields, OrderedDict), 'This logic assumes type of the Form.fields which is suddenly wrong'
        new_fields = fields.__class__()
        for f in fields:
            if f in ['marking', 'review']:
                continue
            new_fields[f] = fields[f]
        new_fields['marking'] = fields['marking']
        new_fields['review'] = fields['review']
        self.fields = new_fields 
Example 26
Project: coursys   Author: sfu-fas   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_make_config_form(self):
        for (name, field_model) in FIELD_TYPE_MODELS.items():
            instance = field_model(self.standard_config)
            config_form = instance.make_config_form()
            # looks like a divider will return a bool false here, look into that
            # still checks for notimplemented error though
            if config_form:
                self.assertTrue(isinstance(config_form, DjangoForm)) 
Example 27
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_config_form(self):
        """
        Returns a Django Form instance that can be used to edit this
        field's details.

        The Form's 'cleaned_data' should match this code's 'config'
        object. 
        
        e.g. user might want to edit the things in the .config field:
        this Form lets them.
        """
        raise NotImplementedError 
Example 28
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 29
Project: GTDWeb   Author: lanbing510   File: helpers.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 30
Project: kobo-predict   Author: awemulya   File: tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_tags_to_instance(request, instance):
    class TagForm(forms.Form):
        tags = TagField()

    form = TagForm(request.data)

    if form.is_valid():
        tags = form.cleaned_data.get('tags', None)

        if tags:
            for tag in tags:
                instance.instance.tags.add(tag)
            instance.save()