Ticket #12582: 12582.diff

File 12582.diff, 2.4 KB (added by Honza Král, 15 years ago)
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 828200c..6833b6d 100644
    a b class ForeignKey(RelatedField, Field):  
    743743        super(ForeignKey, self).validate(value, model_instance)
    744744        if not value:
    745745            return
    746         try:
    747             self.rel.to._default_manager.get(**{self.rel.field_name:value})
    748         except self.rel.to.DoesNotExist, e:
     746
     747        if not self.rel.to._default_manager.filter(**{self.rel.field_name:value}).complex_filter(self.rel.limit_choices_to).exists():
    749748            raise exceptions.ValidationError(
    750749                    self.error_messages['invalid'] % {'model': self.rel.to._meta.verbose_name, 'pk': value})
    751750
  • tests/modeltests/validation/models.py

    diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py
    index f1b0c51..9813be7 100644
    a b class ModelToValidate(models.Model):  
    1212    name = models.CharField(max_length=100)
    1313    created = models.DateTimeField(default=datetime.now)
    1414    number = models.IntegerField()
    15     parent = models.ForeignKey('self', blank=True, null=True)
     15    parent = models.ForeignKey('self', blank=True, null=True, limit_choices_to={'name__startswith': 'Some'})
    1616    email = models.EmailField(blank=True)
    1717    url = models.URLField(blank=True)
    1818    f_with_custom_validator = models.IntegerField(blank=True, null=True, validators=[validate_answer_to_universe])
  • tests/modeltests/validation/tests.py

    diff --git a/tests/modeltests/validation/tests.py b/tests/modeltests/validation/tests.py
    index c00070b..1ec574c 100644
    a b class BaseModelValidationTests(ValidationTestCase):  
    3232        mtv=ModelToValidate(number=10, name='Some Name', parent_id=parent.pk)
    3333        self.assertEqual(None, mtv.full_validate())
    3434
     35    def test_limitted_FK_raises_error(self):
     36        parent = ModelToValidate.objects.create(number=10, name='Other Name')
     37        mtv=ModelToValidate(number=10, name='Some Name', parent_id=parent.pk)
     38        self.assertFailsValidation(mtv.full_validate, ['parent'])
     39
    3540    def test_wrong_email_value_raises_error(self):
    3641        mtv = ModelToValidate(number=10, name='Some Name', email='not-an-email')
    3742        self.assertFailsValidation(mtv.full_validate, ['email'])
Back to Top