Django Admin 3.1.7: getting RelatedObjectDoesNotExist for required ForeignKey

285 views
Skip to first unread message

Olivier

unread,
Mar 29, 2021, 5:02:30 AM3/29/21
to Django users
Hello,

I'm using Django 3.1.7's Admin form of the following model:

class EthernetInterface(models.Model):
    slug_name = models.CharField(max_length=32)
    MAC = MACAddressField(blank=True, null=True)
    lan = models.ForeignKey(LAN, on_delete=models.PROTECT, related_name='lan_interfaces')
    server_host = models.ForeignKey(ServerHost, on_delete=models.PROTECT, related_name='interfaces')
    objects = NetManager()

Admin form displays both Lan and Server host in bold letters.

When I voluntarily forget to supply a LAN object, Admin form displays a red 'This field is required' error message above LAN selection menu. This is what I expected.

When I voluntarily forget to supply a Server Host object, Django throws a RelatedObjectDoesNotExist exception. This is NOT what I expected as I expected it to display a red 'This field is required' error message.

1. Are my expectations correct ?
2. How can I debug or work around this ? (adding a specific rule in model's clean function was not effective as I think this function is called after individuals fields are checked)

Best regards

Olivier

unread,
Mar 30, 2021, 5:35:14 AM3/30/21
to Django users
Hello,

I could source the issue in a line in EthernetInterface clean() function.

Here is the error triggering line:
other_if = EthernetInterface.objects.exclude(server_host__pk=self.server_host.pk).filter(MAC=self.MAC).first()

When I replace this line with ones bellow, behaviour is as expected (red 'This field is required' error message display without any exception throwing):
try:
     other_if = EthernetInterface.objects.exclude(server_host__pk=self.server_host.pk).filter(MAC=self.MAC).first()
except:
     other_if = EthernetInterface.objects.filter(MAC=self.MAC).first()


Though it now works as expected, I'm not satisfied with my workaround because I'm catching all errors or exceptions.


1. Within a clean() function body, what is the canonical way to check if a (required) foreign key is currently set or not ?
I tried with "if self.server_host" without success.
I was thinking of accessing some model dict if such exist.

2. How can I import RelatedObjectDoesNotExist errors in my code ?

3. Would you say that throwing an error when executing a simple "if self.server_host" test is a bug (that should be reported) or not ?

Best regards
Reply all
Reply to author
Forward
0 new messages