django.forms.modelformset_factory

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

6 Examples 7

Example 1

Project: pretix Source File: event.py
    @cached_property
    def formset(self):
        fs = modelformset_factory(
            EventPermission,
            form=EventPermissionForm,
            can_delete=True, can_order=False, extra=0
        )
        return fs(data=self.request.POST if self.request.method == "POST" else None,
                  prefix="formset",
                  queryset=EventPermission.objects.filter(event=self.request.event))

Example 2

Project: orchestra Source File: views.py
    def set_context_data(self, request, *args, **kwargs):
        super().set_context_data(request, *args, **kwargs)
        self.comm_prefs = CommunicationPreference.objects.filter(
            worker=self.worker)
        self.CommunicationPreferenceFormSet = modelformset_factory(
            CommunicationPreference,
            form=CommunicationPreferenceForm,
            extra=0
        )
        self.descriptions = [comm_pref.get_descriptions()
                             for comm_pref in self.comm_prefs]

Example 3

Project: PyClassLessons Source File: forms.py
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max, min_num=min_num,
                                   validate_min=validate_min)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet

Example 4

Project: oioioi Source File: views.py
@enforce_condition(contest_exists & is_teachers_contest & is_contest_admin)
def problem_settings(request, problem_instance_id):
    # Database objects.
    pi = get_object_or_404(ProblemInstance, id=problem_instance_id,
                           contest=request.contest)
    p = pi.problem
    tags = p.tag_set.all()
    attachments = p.attachments.all()
    tests = pi.test_set.all()
    # Formsets
    TestFormset = modelformset_factory(Test, form=TestForm, extra=0)
    PIFormset = modelformset_factory(ProblemInstance,
                                     form=ProblemInstanceForm, extra=0)

    AttachmentFormset = inlineformset_factory(Problem, ProblemAttachment,
                                              extra=0, form=AttachmentForm,
                                              can_delete=True)

    TagFormset = modelformset_factory(Tag, form=TagForm, extra=0,
                                      can_delete=True)

    if request.method == 'POST':
        pif = PIFormset(request.POST, prefix='pif')

        test_formset = TestFormset(request.POST)
        # Bind the clean method, which serves as a time limit validator.
        # http://stackoverflow.com/questions/9646187
        test_formset.get_time_limit_sum = types.MethodType(
                TimeLimitFormset.__dict__['get_time_limit_sum'], test_formset)
        test_formset.validate_time_limit_sum = types.MethodType(
                TimeLimitFormset.__dict__['validate_time_limit_sum'],
                test_formset)
        test_formset.clean = types.MethodType(
                TimeLimitFormset.__dict__['clean'], test_formset)

        attachment_formset = \
            AttachmentFormset(request.POST, request.FILES, instance=p,
                              prefix='attachment')
        tag_formset = TagFormset(request.POST, prefix='tag', queryset=tags)

        if pif.is_valid() and test_formset.is_valid() and \
                attachment_formset.is_valid() and tag_formset.is_valid():

            # Commit is set to False because of errors while deleting.
            instances = attachment_formset.save(commit=False)
            for inst in instances:
                inst.save()
            for inst in attachment_formset.deleted_objects:
                inst.delete()

            # Commit is set to false because we don't want to persist
            # every Tag - we'll be persisting TagThrough instead.
            instances = tag_formset.save(commit=False)
            for inst in instances:
                tag, _ = Tag.objects.get_or_create(name=inst)
                tt = TagThrough()
                tt.problem = p
                tt.tag = tag
                tt.save()
            for inst in tag_formset.deleted_objects:
                TagThrough.objects.filter(tag=inst, problem=p).delete()

            pif.save()
            test_formset.save()
            return redirect(reverse('problem_settings', kwargs={
                'problem_instance_id': problem_instance_id}))

        test_forms = test_formset
        pi_form = pif

    else:
        test_forms = TestFormset(queryset=tests)
        pi_form = PIFormset(queryset=ProblemInstance.objects.filter(id=pi.id),
                            prefix='pif')
        attachment_formset = AttachmentFormset(queryset=attachments,
                                               prefix='attachment',
                                               instance=p)
        tag_formset = TagFormset(prefix='tag', queryset=tags)

    context = {
        'problem_instance': pi,
        'problem': p,
        'tags': tags,
        'attachments': attachments,
        'tests': tests,
        'pi_form': pi_form,
        'test_forms': test_forms,
    }

    for attachment_form in attachment_formset.forms:
        attachment_form.update_link(request.contest.id)
    context['attachment_formset'] = attachment_formset
    context['tag_formset'] = tag_formset

    return TemplateResponse(request,
                            'simpleui/problem_settings/settings.html', context)

Example 5

Project: cgstudiomap Source File: forms.py
Function: generic_inlineformset_factory
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max, min_num=min_num,
                                   validate_min=validate_min)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet

Example 6

Project: django Source File: forms.py
Function: generic_inlineformset_factory
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(
        model, form=form, formfield_callback=formfield_callback,
        formset=formset, extra=extra, can_delete=can_delete,
        can_order=can_order, fields=fields, exclude=exclude, max_num=max_num,
        validate_max=validate_max, min_num=min_num, validate_min=validate_min,
    )
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet