Tuesday, March 30, 2021

How to test foreign key in clean() [was: Django Admin 3.1.7: getting RelatedObjectDoesNotExist for required ForeignKey]

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

Le lundi 29 mars 2021 à 11:02:30 UTC+2, Olivier a écrit :
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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/85f04480-82ac-4ed4-bd90-4ebee8bbd601n%40googlegroups.com.

No comments:

Post a Comment