我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用django.forms.models.modelformset_factory()。
def process_modelformset(request, model_class, queryset, **kwargs): """With the Django model class `model_class` and the given `queryset`, construct a formset process its submission. """ # Create a formset class for the model `model_class` (i.e. it will contain # forms whose contents are based on the fields of `model_class`); # parameters for the construction of the forms used in the formset should # be in kwargs. formset_class = modelformset_factory(model_class, **kwargs) if queryset is None: queryset = model_class.objects.all() # If the request is a POST, we want to possibly update our data if request.method == 'POST' and request.POST: # Create a formset from all the 'model_class' instances whose values # will be updated using the contents of request.POST objects = paginate(request, queryset) formset = formset_class(request.POST, queryset=objects.object_list) # Validate all the forms in the formset if formset.is_valid(): # If all is well, Django can save all our data for us formset.save() else: # Otherwise, complain to the user that something went wrong return formset, _("There are errors in the form. Please review " "the problems below."), objects # Hack to force reevaluation of same query queryset = queryset.filter() objects = paginate(request, queryset) return formset_class(queryset=objects.object_list), None, objects
def change_faircoin_account(request, resource_id): #import pdb; pdb.set_trace() if request.method == "POST": resource = get_object_or_404(EconomicResource, pk=resource_id) form = EconomicResourceForm(data=request.POST, instance=resource) if form.is_valid(): data = form.cleaned_data resource = form.save(commit=False) resource.changed_by=request.user resource.save() """ RraFormSet = modelformset_factory( AgentResourceRole, form=ResourceRoleAgentForm, can_delete=True, extra=4, ) role_formset = RraFormSet( prefix="role", queryset=resource.agent_resource_roles.all(), data=request.POST ) if role_formset.is_valid(): saved_formset = role_formset.save(commit=False) for role in saved_formset: role.resource = resource role.save() """ return HttpResponseRedirect('/%s/%s/' % ('work/manage-faircoin-account', resource_id)) else: raise ValidationError(form.errors)
def unscheduled_time_contributions(request): member = get_agent(request) if not member: return HttpResponseRedirect('/%s/' % ('accounting/work')) TimeFormSet = modelformset_factory( EconomicEvent, form=CasualTimeContributionForm, can_delete=False, extra=8, max_num=8, ) init = [] for i in range(0, 8): init.append({"is_contribution": True,}) time_formset = TimeFormSet( queryset=EconomicEvent.objects.none(), initial = init, data=request.POST or None) if request.method == "POST": #import pdb; pdb.set_trace() keep_going = request.POST.get("keep-going") just_save = request.POST.get("save") if time_formset.is_valid(): events = time_formset.save(commit=False) pattern = None patterns = PatternUseCase.objects.filter(use_case__identifier='non_prod') if patterns: pattern = patterns[0].pattern else: raise ValidationError("no non-production ProcessPattern") if pattern: unit = Unit.objects.filter( unit_type="time", name__icontains="Hour")[0] for event in events: if event.event_date and event.quantity: event.from_agent=member event.to_agent = event.context_agent.default_agent() #event.is_contribution=True rt = event.resource_type event_type = pattern.event_type_for_resource_type("work", rt) event.event_type=event_type event.unit_of_quantity=unit event.created_by=request.user event.save() if keep_going: return HttpResponseRedirect('/%s/' % ('accounting/unscheduled-time')) else: return HttpResponseRedirect('/%s/%s/' % ('accounting/contributionhistory', member.id)) return render_to_response("valueaccounting/unscheduled_time_contributions.html", { "member": member, "time_formset": time_formset, "help": get_help("non_production"), }, context_instance=RequestContext(request))
def resource_role_agent_formset(prefix, data=None): #import pdb; pdb.set_trace() RraFormSet = modelformset_factory( AgentResourceRole, form=ResourceRoleAgentForm, can_delete=True, extra=4, ) formset = RraFormSet(prefix=prefix, queryset=AgentResourceRole.objects.none(), data=data) return formset
def change_resource(request, resource_id): #import pdb; pdb.set_trace() if request.method == "POST": resource = get_object_or_404(EconomicResource, pk=resource_id) v_help = None if resource.resource_type.unit_of_use: v_help = "give me a usable widget" form = EconomicResourceForm(data=request.POST, instance=resource, vpu_help=v_help) if form.is_valid(): data = form.cleaned_data resource = form.save(commit=False) resource.changed_by=request.user resource.save() RraFormSet = modelformset_factory( AgentResourceRole, form=ResourceRoleAgentForm, can_delete=True, extra=4, ) role_formset = RraFormSet( prefix="role", queryset=resource.agent_resource_roles.all(), data=request.POST ) if role_formset.is_valid(): saved_formset = role_formset.save(commit=False) for role in saved_formset: role.resource = resource role.save() return HttpResponseRedirect('/%s/%s/' % ('accounting/resource', resource_id)) else: raise ValidationError(form.errors)
def update_shops(request): ShopFormSet = modelformset_factory(Shop, fields=('title', 'domain', 'sync_type', 'key'), extra=0) formset = ShopFormSet(queryset=Shop.objects.filter(user=request.user)) return direct_to_template(request, "partial/shops_formset.html", {"formset": formset})
def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(MainView, self).get_context_data(**kwargs) context['form'] = LoadDataForm(error_class=DivErrorList, request=self.request) context['add_form'] = AddShopForm() ShopFormSet = modelformset_factory(Shop, fields=('title', 'domain', 'sync_type', 'key'), extra=0) formset = ShopFormSet(queryset=context['shop_list']) context['formset'] = formset return context
def change_pattern(request, pattern_id, use_case_id): pattern = get_object_or_404(ProcessPattern, id=pattern_id) use_case = get_object_or_404(UseCase, id=use_case_id) slots = use_case.allowed_event_types() #import pdb; pdb.set_trace() for slot in slots: slot.resource_types = pattern.get_resource_types(slot) slot.facets = pattern.facets_for_event_type(slot) FacetValueFormSet = modelformset_factory( PatternFacetValue, form=PatternFacetValueForm, can_delete=True, extra=2, ) facet_value_formset = FacetValueFormSet( queryset=slot.facets, data=request.POST or None, prefix=slot.slug) slot.formset = facet_value_formset slot.rts = ResourceTypeSelectionForm( qs=slot.resource_types, prefix=slot.slug) #import pdb; pdb.set_trace() slot_ids = [slot.id for slot in slots] if request.method == "POST": #import pdb; pdb.set_trace() for slot in slots: for form in slot.formset: if form.is_valid(): data = form.cleaned_data old_value = data.get("id") new_value = data.get("facet_value") if old_value: if data["DELETE"]: old_value.delete() elif old_value.facet_value != new_value: if new_value: form.save() elif new_value: if not data["DELETE"]: fv = PatternFacetValue( pattern=pattern, event_type=slot, facet_value=new_value) fv.save() return HttpResponseRedirect('/%s/%s/%s/' % ('accounting/change-pattern', pattern.id, use_case.id)) return render_to_response("valueaccounting/change_pattern.html", { "pattern": pattern, "slots": slots, "use_case": use_case, }, context_instance=RequestContext(request))
def test_modelformset_layout(self): CrispyModelFormSet = modelformset_factory(CrispyTestModel, form=TestForm4, extra=3) formset = CrispyModelFormSet(queryset=CrispyTestModel.objects.none()) helper = FormHelper() helper.layout = Layout( 'email' ) html = render_crispy_form(form=formset, helper=helper) self.assertEqual(html.count("id_form-0-id"), 1) self.assertEqual(html.count("id_form-1-id"), 1) self.assertEqual(html.count("id_form-2-id"), 1) django_version = django.get_version() if django_version < '1.5': self.assertEqual(html.count( 'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"' ), 1) self.assertEqual(html.count( 'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"' ), 1) if (django_version >= '1.4' and django_version < '1.4.4') or django_version < '1.3.6': self.assertEqual(html.count( 'type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual(html.count( 'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual(html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ), 1) self.assertEqual(html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ), 1) self.assertEqual(html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ), 1) self.assertEqual(html.count('name="form-0-email"'), 1) self.assertEqual(html.count('name="form-1-email"'), 1) self.assertEqual(html.count('name="form-2-email"'), 1) self.assertEqual(html.count('name="form-3-email"'), 0) self.assertEqual(html.count('password'), 0)