Opened 14 years ago
Closed 14 years ago
#14059 closed (duplicate)
ForeignKey Field validates using the default database rather than the current model instance's database
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Forms | Version: | 1.2 |
Severity: | Keywords: | multipledatabases | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
When using multiple databases, ForeignKey fields can be setup to pull their options from a specific database.
ForeignKey.formfield({ 'using' : 'NotDefault' }).
However when validating the form, the ForeignKey fields do not validate using the associated database.
Current form validation method incorrectly validates ForeignKey relationships using the default manager instead of the model instances' database.
Django 1.2 Code: django.db.models.fields.related.py
class ForeignKey(RelatedField, Field): def validate(self, value, model_instance): if self.rel.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return qs = self.rel.to._default_manager.filter(**{self.rel.field_name:value}) qs = qs.complex_filter(self.rel.limit_choices_to) if not qs.exists(): raise exceptions.ValidationError(self.error_messages['invalid'] % { 'model': self.rel.to._meta.verbose_name, 'pk': value})
Proposed change will using the model_instances' database instance of the default manager.
As you can see self.rel.to._default_manager becomes self.rel.to._default_manager.using(model_instance._state.db).
def validate(self, value, model_instance): if self.rel.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return qs = self.rel.to._default_manager.using(model_instance._state.db).filter(**{self.rel.field_name:value}) qs = qs.complex_filter(self.rel.limit_choices_to) if not qs.exists(): raise exceptions.ValidationError(self.error_messages['invalid'] % { 'model': self.rel.to._meta.verbose_name, 'pk': value})
Duplicate of #14691 (That is newer but got picked and fixed first). Thanks for the report and fix suggestion.