Python django.forms.modelform_factory() Examples

The following are 17 code examples for showing how to use django.forms.modelform_factory(). 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: gatorgrouper   Author: GatorIncubator   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_classes(request):
    """ Create classes view """
    ClassFormSet = modelform_factory(
        Semester_Class,
        fields=("semester", "department", "class_number", "class_section"),
    )
    if request.method == "POST":
        formset = ClassFormSet(request.POST)
        if formset.is_valid():
            stock = formset.save(commit=False)
            stock.professor_id = request.user
            stock.save()
            messages.success(request, f"Class Added")
            return redirect("profile")
    else:
        formset = ClassFormSet()

    return render(
        request,
        "gatorgrouper/classes.html",
        {"title": "Create Classes", "formset": formset},
    )


# Allows the user to view the list of assignments 
Example 2
Project: django-radio   Author: iago1460   File: test_schedules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.CalendarForm = modelform_factory(Calendar, fields=("name",)) 
Example 3
Project: byro   Author: byro   File: settings.py    License: Apache License 2.0 5 votes vote down vote up
def get_form(self):
        config_models = [
            model for model in apps.get_models() if issubclass(model, ByroConfiguration)
        ]
        data = self.request.POST if self.request.method == "POST" else None
        return [
            forms.modelform_factory(
                model, fields="__all__", exclude=("registration_form",)
            )(prefix=model.__name__, instance=model.get_solo(), data=data)
            for model in config_models
        ] 
Example 4
Project: PonyConf   Author: PonyConf   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_form_class(self):
        return modelform_factory(
                    self.model,
                    form=ParticipantForm,
                    fields=['name', 'vip', 'email', 'phone_number', 'biography', 'notes'] + ParticipantForm.SOCIAL_FIELDS,
        ) 
Example 5
Project: PonyConf   Author: PonyConf   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_form_class(self):
        return modelform_factory(
                    self.model,
                    form=ParticipantForm,
                    fields=['name', 'vip', 'email', 'phone_number', 'biography', 'notes'] + ParticipantForm.SOCIAL_FIELDS,
        ) 
Example 6
Project: django-collaborative   Author: propublica   File: admin.py    License: MIT License 5 votes vote down vote up
def widget_for_object_field(obj, field_name):
    FieldForm = modelform_factory(
        obj.source_dynmodel().get_model(),
        fields=(field_name,)
    )
    widget = FieldForm().fields[field_name].widget
    return widget 
Example 7
Project: colossus   Author: vitorfs   File: views.py    License: MIT License 5 votes vote down vote up
def get_form_class(self):
        fields = self.object.settings['fields']
        form_class = modelform_factory(self.model, fields=fields)
        return form_class 
Example 8
Project: Inboxen   Author: Inboxen   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_page_form(model_ct, form=HelpBasePageForm):
    model = model_ct.model_class()
    assert issubclass(model, models.HelpBasePage) and model != models.HelpBasePage, \
        "Model must be a subclass of HelpBasePage, but not HelpBasePage itself."
    assert model in PAGE_TYPES, "Not a supported model"

    form = forms.modelform_factory(model, form=form, fields=model.admin_fields)
    form.model_ct = model_ct

    return form 
Example 9
Project: djongo   Author: nesdis   File: fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_model_form_class(model_form_class, model_container, admin, request):
    if not model_form_class:
        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_class = modelform_factory(model_container, **form_kwargs)

    return model_form_class 
Example 10
Project: django-phone-field   Author: VeryApt   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_rendering(self):
        Form = modelform_factory(TestModel, fields=('phone',))
        obj = TestModel(phone='415 123 4567 x 88')
        f = Form(instance=obj)
        self.assertEqual(str(f), _rendered_field_html(phone_number='(415) 123-4567', extension='88', required=True)) 
Example 11
Project: django-phone-field   Author: VeryApt   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_rendering_nullable(self):
        Form = modelform_factory(TestModelBlankNull, fields=('phone',))
        obj = TestModel(phone='415 123 4567 x 88')
        f = Form(instance=obj)
        self.assertEqual(str(f), _rendered_field_html(phone_number='(415) 123-4567', extension='88', required=False)) 
Example 12
Project: django-phone-field   Author: VeryApt   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_saving(self):
        Form = modelform_factory(TestModel, fields=('phone',))
        f = Form({'phone_0': '415.123.4567', 'phone_1': '88'})
        self.assertTrue(f.is_valid())
        obj = f.save()
        self.assertIsInstance(obj.phone, PhoneNumber)
        self.assertEqual(str(obj.phone), '(415) 123-4567, press 88') 
Example 13
Project: django-phone-field   Author: VeryApt   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_rendering(self):
        Form = modelform_factory(TestModelOptional, fields=('phone',))
        obj = TestModelOptional(phone='415 123 4567 x 88')
        f = Form(instance=obj)
        self.assertEqual(str(f), _rendered_field_html(phone_number='(415) 123-4567', extension='88', required=False)) 
Example 14
Project: django-phone-field   Author: VeryApt   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_empty(self):
        Form = modelform_factory(TestModelOptional, fields=('name', 'phone'))
        f = Form({'name': 'Ted', 'phone_0': '', 'phone_1': ''})
        self.assertTrue(f.is_valid())
        obj = f.save()
        self.assertEqual(obj.phone, '') 
Example 15
Project: MetaCI   Author: SFDO-Tooling   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_form_class(self):
        return modelform_factory(self.model, form=AddNotificationForm) 
Example 16
Project: byro   Author: byro   File: members.py    License: Apache License 2.0 4 votes vote down vote up
def get_forms(self):
        obj = self.get_object()
        membership_create_form = forms.modelform_factory(
            Membership, fields=["start", "end", "interval", "amount"]
        )
        for key in membership_create_form.base_fields:
            setattr(membership_create_form.base_fields[key], "required", False)
        return (
            [
                self._instantiate(
                    forms.modelform_factory(Member, exclude=["membership_type"]),
                    member=obj,
                    instance=obj,
                )
            ]
            + [
                self._instantiate(
                    forms.modelform_factory(Membership, exclude=["member"]),
                    member=obj,
                    instance=m,
                    prefix=m.id,
                )
                for m in obj.memberships.all()
            ]
            + [
                self._instantiate(
                    membership_create_form,
                    member=obj,
                    profile_class=Membership,
                    empty=True,
                )
            ]
            + [
                self._instantiate(
                    forms.modelform_factory(
                        profile_class,
                        fields=[
                            f.name
                            for f in profile_class._meta.fields
                            if f.name not in ["id", "member"]
                        ],
                    ),
                    member=obj,
                    profile_class=profile_class,
                )
                for profile_class in obj.profile_classes
            ]
        ) 
Example 17
Project: website   Author: outreachy   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def get_form_class(self):
        # We want to have different fields for different comrades, but
        # self.fields is shared across all instances of this view, so we can't
        # use that. There's no get_fields() method we can override, either, so
        # the only hook we can use is overriding this method of ModelFormMixin.
        fields = [
            'public_name',
            'nick_name',
            'legal_name',
            'pronouns',
            'pronouns_to_participants',
            'pronouns_public',
        ]

        comrade = self.object

        # was an approved coordinator for a community that had at least one approved participation
        coordinatored = comrade.coordinatorapproval_set.approved().filter(
            community__participation__approval_status=ApprovalStatus.APPROVED,
        )
        # was an approved mentor for some approved project in an approved community
        mentored = comrade.get_mentored_projects().approved().filter(
            project_round__approval_status=ApprovalStatus.APPROVED,
        )
        # was an approved application reviewer at some point
        reviewered = comrade.applicationreviewer_set.approved()

        # people who participated in some way at some time can set a photo of themselves
        if comrade.account.is_staff or comrade.get_intern_selection() is not None or coordinatored.exists() or mentored.exists() or reviewered.exists():
            fields.append('photo')

        fields.extend([
            'timezone',
            'location',
            'nick',
            'github_url',
            'gitlab_url',
            'blog_url',
            'blog_rss_url',
            'twitter_url',
            'agreed_to_code_of_conduct',
        ])
        return modelform_factory(comrade.__class__, fields=fields)