From 482e350ab6f7af5999663903f9c2cdf9578588de Mon Sep 17 00:00:00 2001 From: Vicente Olivert Riera Date: Wed, 15 May 2024 11:24:02 +0900 Subject: [PATCH] Fix testing Rule query before saving When creating a new Rule and testing its query before saving it, an error like this was happening: 'Rule' instance needs to have a primary key value before this relationship can be used. From the user's perspective, the test was not happening and the server returned a 500 error. When testing a new Rule that has not been saved, a temporary Rule object is created in memory. Since that object is not saved, it does not contain a primary key. Due to some changes introduced in Django 4, errors are thrown if that object without a primary key is used. To fix that issue, we manually assign a primary key. --- promgen/views.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/promgen/views.py b/promgen/views.py index 4d62efa3c..53963c8f2 100644 --- a/promgen/views.py +++ b/promgen/views.py @@ -1288,6 +1288,13 @@ class RuleTest(LoginRequiredMixin, View): def post(self, request, pk): if pk == 0: rule = models.Rule() + # In Django https://code.djangoproject.com/ticket/19580, some of the + # foreign key checks got stricter. We sets pk to 0 here so that it passes + # django's m2m/foreign key checks, but marks for us that it's a temporary + # rule that doesn't actually exist. + # We'll likely want to rework this assumption when we move to a different + # promql check + rule.pk = 0 rule.set_object(request.POST["content_type"], request.POST["object_id"]) else: rule = get_object_or_404(models.Rule, id=pk)