Code

Opened 4 years ago

Closed 3 years ago

#14059 closed (duplicate)

ForeignKey Field validates using the default database rather than the current model instance's database

Reported by: pseidel@… 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: UI/UX:

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})

Attachments (0)

Change History (1)

comment:1 Changed 3 years ago by ramiro

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to closed

Duplicate of #14691 (That is newer but got picked and fixed first). Thanks for the report and fix suggestion.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.