Opened 8 years ago

Closed 8 years ago

Last modified 5 years ago

#7908 closed (fixed)

A ForeignKey of an abstract class can fail to validate

Reported by: rockmhoward@… Owned by: nobody
Component: Core (Other) Version: master
Severity: Keywords: ForeignKey abstract
Cc: mk@… Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


A model with a ForeignKey relating to an abstract class fails to validate by crashing in line 605.

The example is attached or see:

The traceback from validate:

Attachments (3) (815 bytes) - added by rock@… 8 years ago.
a file that fails during validation (402 bytes) - added by rock@… 8 years ago.
7908.patch (610 bytes) - added by mk 8 years ago.

Download all attachments as: .zip

Change History (8)

Changed 8 years ago by rock@…

a file that fails during validation

comment:1 Changed 8 years ago by rock@…

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

I tried adding a guard by replacing the offending line 605 as follows:

to_field = to_field
if to_field == None:

if is None:

raise ValueError("The %s model does not have a primary key and therefore a ForeignKey cannot relate to it." % to_name)

to_field =

This is not a real fix as the validate command still crashes, but the error message is a bit nicer. A real fix has to go in the validate code.

Changed 8 years ago by rock@…

Changed 8 years ago by mk

comment:2 Changed 8 years ago by mk

  • Cc mk@… added
  • Has patch set
  • Triage Stage changed from Unreviewed to Ready for checkin

The attached patch gives a better(?) error message for both ForeignKey and ManyToManyField, using the syntax above and also using f.e. mine = models.ManyToManyField('Attachment') (lazy loading)

comment:3 Changed 8 years ago by mtredinnick

  • milestone set to 1.0

comment:4 Changed 8 years ago by russellm

  • Resolution set to fixed
  • Status changed from new to closed

(In [8442]) Fixed #7908: Added validation checks on attempts to create ForeignKey and M2M relations with abstract classes. Thanks to Rock Howard for the report.

comment:5 Changed 5 years ago by jacob

  • milestone 1.0 deleted

Milestone 1.0 deleted

Note: See TracTickets for help on using tickets.
Back to Top