Ticket #13677: 13677.diff
File 13677.diff, 3.1 KB (added by , 14 years ago) |
---|
-
django/forms/models.py
236 236 class BaseModelForm(BaseForm): 237 237 def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, 238 238 initial=None, error_class=ErrorList, label_suffix=':', 239 empty_permitted=False, instance=None ):239 empty_permitted=False, instance=None, using=None): 240 240 opts = self._meta 241 241 if instance is None: 242 242 if opts.model is None: … … 259 259 super(BaseModelForm, self).__init__(data, files, auto_id, prefix, object_data, 260 260 error_class, label_suffix, empty_permitted) 261 261 262 # correct the choices queryset.using for choice fields 263 if using is None and instance is not None: 264 using = instance._state.db 265 if using is not None: 266 model_choice_fields = filter(lambda f: isinstance(f, ModelChoiceField), self.fields.values()) 267 for field in model_choice_fields: 268 field.queryset = field.queryset.using(using) 269 262 270 def _update_errors(self, message_dict): 263 271 for k, v in message_dict.items(): 264 272 if k != NON_FIELD_ERRORS: … … 451 459 kwargs['instance'] = self._existing_object(pk) 452 460 if i < self.initial_form_count() and not kwargs.get('instance'): 453 461 kwargs['instance'] = self.get_queryset()[i] 462 kwargs['using'] = self.get_queryset()._db 454 463 return super(BaseModelFormSet, self)._construct_form(i, **kwargs) 455 464 456 465 def get_queryset(self): -
tests/regressiontests/multiple_database/tests.py
1759 1759 b.authors.clear() 1760 1760 self._write_to_default() 1761 1761 self.assertEqual(receiver._database, "other") 1762 1763 class ModelFormsetUsingTestCase(TestCase): 1764 multi_db = True 1765 1766 def test_formset_using(self): 1767 author = Person.objects.using('other').create(name="Marty Alchin") 1768 editor = Person.objects.using('other').create(name="George Vilches") 1769 b = Book.objects.using('other').create(title="Pro Django", 1770 published=datetime.date(2008, 12, 16), 1771 editor=editor) 1772 b.authors.add(author) 1773 1774 from django import forms 1775 from django.forms.models import modelformset_factory 1776 class BookForm(forms.ModelForm): 1777 class Meta: 1778 model = Book 1779 formset_class = modelformset_factory(Book, BookForm) 1780 formset = formset_class(queryset=Book.objects.using('other').all()) 1781 for form in formset.forms: 1782 databases = [i._state.db for i in form.fields['editor'].queryset] 1783 databases.extend([i._state.db for i in form.fields['authors'].queryset]) 1784 self.assertEqual(set(databases), set(['other'])) 1785 No newline at end of file