This question is similar to Set model field choices attribute at run time? However, my problem is that I want to change the default value of the choices attribute, at class level.
I have this
class Project(models.Model):
name = models.CharField(...)
@staticmethod
def getAllProjectsTuple():
return tuple([(p.id, p.name) for p in Project.objects.all()])
class Record(models.Model):
project = models.ForeignKey(
Project,
verbose_name='Project',
help_text='Project name',
blank=True, null=True,
on_delete=models.SET_NULL,
choices = Project.getAllProjectsTuple(),
class RecordForm(ModelForm):
class Meta:
model = Record
My problem is that all the RecordForm will be created with a TypedChoiceField using the available choices that were in the model at the time of the module import. However, users can create more projects, and those will never appear in the RecordForm; same for deletion.
I tried tampering directly with the init of the RecordForm:
self.fields['project']._choices = [('', '---------'),] + [(p.id, p.name) for p in Project.objects.all()]
or with the init of the Record:
self._meta.get_field('project')._choices = Project.getAllProjectsTuple()
but nothing seems to work.
Thanks for your help.