我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.modelformset_factory()。
def test_both_labels_are_required(self): ContactClassifierLabel.objects.all().update(required=True) ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) contact_formset = ContactFormSet( queryset=Contact.objects.all() ) self.assertEqual(len(contact_formset.forms), 2) self.assertIn( {'kind': self.label_mobile.pk}, [f.initial for f in contact_formset.forms], ) self.assertIn( {'kind': self.label_work.pk}, [f.initial for f in contact_formset.forms], )
def test_mobile_is_required(self): self.label_mobile.required = True self.label_mobile.save() ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) contact_formset = ContactFormSet( queryset=Contact.objects.all() ) self.assertEqual(len(contact_formset.forms), 1) self.assertIn( {'kind': self.label_mobile.pk}, [f.initial for f in contact_formset.forms], ) self.assertNotIn( {'kind': self.label_work.pk}, [f.initial for f in contact_formset.forms], )
def test_initial_as_dict(self): ContactClassifierLabel.objects.all().update(required=True) ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) contact_formset = ContactFormSet( queryset=Contact.objects.all(), initial={ 'user': 43, } ) self.assertEqual(len(contact_formset.forms), 2) self.assertIn( {'user': 43, 'kind': self.label_mobile.pk}, [f.initial for f in contact_formset.forms], ) self.assertIn( {'user': 43, 'kind': self.label_work.pk}, [f.initial for f in contact_formset.forms], )
def test_initial_as_dict_with_default_behaviour(self): ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) contact_formset = ContactFormSet( queryset=Contact.objects.all(), initial={'user': 41} ) self.assertEqual(len(contact_formset.forms), 1) self.assertIn( {'user': 41}, [f.initial for f in contact_formset.forms], )
def test_one_label_required(self): self.label_mobile.required = True self.label_mobile.save() ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) data = {} data.update(self.get_management_form()) contact_formset = ContactFormSet(data, queryset=Contact.objects.all()) self.assertFalse(contact_formset.is_valid()) self.assertEqual(len(contact_formset.non_form_errors()), 1) self.assertIn( six.text_type(self.label_mobile), contact_formset.non_form_errors()[0] )
def test_two_labels_required(self): ContactClassifierLabel.objects.all().update(required=True) ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) data = {} data.update(self.get_management_form(2)) contact_formset = ContactFormSet(data, queryset=Contact.objects.all()) self.assertFalse(contact_formset.is_valid()) self.assertEqual(len(contact_formset.non_form_errors()), 1) labels = [self.label_mobile, self.label_work] error_msg = contact_formset.non_form_errors()[0] self.assertTrue(any([ ', '.join(map(six.text_type, labels)) in error_msg, ', '.join(map(six.text_type, labels[::-1])) in error_msg, ]))
def test_classifier_required(self): self.classifier.only_one_required = True self.classifier.save() ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) data = {} data.update(self.get_management_form()) contact_formset = ContactFormSet(data, queryset=Contact.objects.all()) self.assertFalse(contact_formset.is_valid()) self.assertEqual(len(contact_formset.non_form_errors()), 1) self.assertIn( '/'.join(map(six.text_type, [self.label_mobile, self.label_work])), contact_formset.non_form_errors()[0] )
def test_one_required_label_present(self): ContactClassifierLabel.objects.all().update(required=True) ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) data = { 'form-0-user': self.user.pk, 'form-0-kind': self.label_mobile.pk, 'form-0-value': '5555555' } data.update(self.get_management_form()) contact_formset = ContactFormSet(data, queryset=Contact.objects.all()) self.assertFalse(contact_formset.is_valid()) self.assertEqual(len(contact_formset.non_form_errors()), 1) self.assertIn( six.text_type(self.label_work), contact_formset.non_form_errors()[0] )
def post(self, request, id): ImageFormSet = modelformset_factory(BluePrints, form=BluePrintForm, extra=5) formset = ImageFormSet(request.POST, request.FILES, queryset=BluePrints.objects.none()) if formset.is_valid(): for form in formset.cleaned_data: if 'image' in form: image = form['image'] photo = BluePrints(site_id=id, image=image) photo.save() messages.success(request, "Blueprints saved!") return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': id})) formset = ImageFormSet(queryset=BluePrints.objects.none()) return render(request, 'fieldsight/blueprints_form.html', {'formset': formset, 'id': self.kwargs.get('id')}, )
def get_formset(self, clear=False): CartItemFormSet = modelformset_factory( CartItem, fields=('quantity',), can_delete=True, extra=0 ) session_key = self.request.session.session_key if session_key: if clear: formset = CartItemFormSet( queryset=CartItem.objects.filter(cart_key=session_key) ) else: formset = CartItemFormSet( queryset=CartItem.objects.filter(cart_key=session_key), data=self.request.POST or None ) else: formset = CartItemFormSet(queryset=CartItem.objects.none()) return formset
def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) slug = self.kwargs.get('slug', '') goals = get_object_or_404(Goals, slug = slug) MyGoalsFormset = modelformset_factory(MyGoals, form = MyGoalsForm, extra = 0) my_goals_formset = MyGoalsFormset(self.request.POST, queryset = MyGoals.objects.filter(user = request.user, item__goal = goals)) if (my_goals_formset.is_valid()): return self.form_valid(my_goals_formset) else: return self.form_invalid(my_goals_formset)
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
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
def test_one_of_label_is_required(self): self.classifier.only_one_required = True self.classifier.save() self.assertFalse( ContactClassifierLabel.objects.filter(required=True).exists() ) ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) contact_formset = ContactFormSet( queryset=Contact.objects.all() ) self.assertEqual(len(contact_formset.forms), 1) self.assertIn( {'kind': self.label_mobile.pk}, [f.initial for f in contact_formset.forms], ) self.assertNotIn( {'kind': self.label_work.pk}, [f.initial for f in contact_formset.forms], )
def test_initial_as_list(self): ContactClassifierLabel.objects.all().update(required=True) ContactFormSet = modelformset_factory( Contact, formset=ClassifierFormSet, fields=('id', 'user', 'kind', 'value', ) ) contact_formset = ContactFormSet( queryset=Contact.objects.all(), initial=[ {'user': 41}, {'user': 42}, ] ) self.assertEqual(len(contact_formset.forms), 2) self.assertIn( {'user': 41, 'kind': self.label_mobile.pk}, [f.initial for f in contact_formset.forms], ) self.assertIn( {'user': 42, 'kind': self.label_work.pk}, [f.initial for f in contact_formset.forms], )
def test_no_relation_to_label(self): UserModel = get_user_model() UserFormSet = modelformset_factory( UserModel, formset=ClassifierFormSet, fields=('id', 'email', ) ) self.assertRaises( ClassifierLabelModelNotFound, UserFormSet, queryset=UserModel.objects.all() )
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
def _createMultiChoiceAnswerFormSet(request, queryset): form = modelformset_factory(MultiChoiceAnswer, form=MultiChoiceAnswerForm, extra=0) return form(request.POST or None, queryset=queryset, )
def _createOpenAnswerFormSet(request, queryset): form = modelformset_factory(OpenAnswer, form=OpenAnswerForm, extra=0) return form(request.POST or None, queryset=queryset, )
def get(self, request, *args, **kwargs): ImageFormSet = modelformset_factory(BluePrints, form=BluePrintForm, extra=5) formset = ImageFormSet(queryset=BluePrints.objects.none()) return render(request, 'fieldsight/blueprints_form.html', {'formset': formset,'id': self.kwargs.get('id')},)
def get_formset_class(self): return self.formset_class or modelformset_factory(model=self.formset_model, fields='__all__', can_delete=True)
def formset_view(request): if request.user.is_authenticated(): PostModelFormset = modelformset_factory(Post, form=PostModelForm) formset = PostModelFormset(request.POST or None, queryset=Post.objects.filter(user=request.user)) if formset.is_valid(): #formset.save(commit=False) for form in formset: print(form.cleaned_data) obj = form.save(commit=False) if form.cleaned_data: #obj.title = "This title %s" %(obj.id) if not form.cleaned_data.get("publish"): obj.publish = timezone.now() obj.save() # return redirect("/") #print(form.cleaned_data) context = { "formset": formset } return render(request, "formset_view.html", context) else: raise Http404 # def formset_view(request): # TestFormset = formset_factory(TestForm, extra=2) # formset = TestFormset(request.POST or None) # if formset.is_valid(): # for form in formset: # print(form.cleaned_data) # context = { # "formset": formset # } # return render(request, "formset_view.html", context)
def dynamic_modelformset_factory(*args, **kwargs): kwargs.update({ 'formset': DynamicModelFormSet }) modelformset = forms.modelformset_factory(*args, **kwargs) return modelformset
def edit_all_products(request): ProductFormSet = modelformset_factory(Product, fields=('name', 'price', 'category'), extra=0) data = request.POST or None formset = ProductFormSet(data=data, queryset=Product.objects.filter(user=request.user)) for form in formset: form.fields['category'].queryset = Category.objects.filter(user=request.user) if request.method == 'POST' and formset.is_valid(): formset.save() return redirect('products_list') return render(request, 'products/products_formset.html', {'formset': formset})
def test_modelformset_pass_locales_down(): a = Author.objects.create(name='Tolkien') title = 'The Lord of the Rings' abstract = 'Frodo tries to destroy a ring' Book.objects.create(author=a, title=title, abstract=abstract) FormSetClass = modelformset_factory(Book, form=BookForm, formset=I18nModelFormSet) fs = FormSetClass(locales=['de', 'fr'], queryset=Book.objects.all()) assert fs.forms[0].fields['title'].widget.enabled_locales == ['de', 'fr'] assert fs.empty_form.fields['title'].widget.enabled_locales == ['de', 'fr']
def get(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) slug = self.kwargs.get('slug', '') goals = get_object_or_404(Goals, slug = slug) MyGoalsFormset = modelformset_factory(MyGoals, form = MyGoalsForm, extra = 0) my_goals_formset = MyGoalsFormset(queryset = MyGoals.objects.filter(user = request.user, item__goal = goals)) return self.render_to_response(self.get_context_data(my_goals_formset = my_goals_formset))
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.total_deal_price = 0 self.ProductFormset = modelformset_factory(model=DealProducts, form=DealProductForm, extra=1, can_delete=True) self.StatusFormset = modelformset_factory(model=DealStatus, form=DealStatusForm, extra=1, can_delete=True)