To test you can use the below models, form and unit test
{{{
# models.py
from django.db import models
class Tag(models.Model):
tag = models.SlugField(max_length=64, unique=True)
class Thing(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE,
related_name="things")
active = models.BooleanField(default=True)
}}}
{{{
# forms.py
from django import forms
from example.models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = ["tag"]
def __init__(self, *args, **kwargs):
super(TagForm, self).__init__(*args, **kwargs)
if self.instance and self.instance.things:
inactive_things = self.instance.things.filter(active=False)
# Do something with it
}}}
{{{
from unittest.case import TestCase
from example.forms import TagForm
class TagFormCase(TestCase):
def test_required(self):
"""Test required fields"""
form = TagForm({})
self.assertFalse(form.is_valid())
self.assertEqual(
{
"tag": ["This field is required."],
},
form.errors,
)
}}}
If you run the test on Django versions <4.1 including Django 2.*, Django
3.* and 4.0.* then it'll pass but on 4.1.* it'll fail with ```ValueError:
'Tag' instance needs to have a primary key value before this relationship
can be used.```
In order to pass the if statement needs to be changed to ```if
self.instance.pk and self.instance.things``` as self.instance is no longer
None if no instance is passed in.
If your model uses a custom primary key such as a uuid4 then it'll work as
expected as the uuid4 is already called
--
Ticket URL: <https://code.djangoproject.com/ticket/34084>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* component: Database layer (models, ORM) => Forms
--
Ticket URL: <https://code.djangoproject.com/ticket/34084#comment:1>
* cc: David Kwong (added)
--
Ticket URL: <https://code.djangoproject.com/ticket/34084#comment:2>