Thank you for pointing it out. What I forgot to mention is that field1 is a ForeignKey to other model which means is type of ModelChoiceField, Is it possible to still explicitly set default value to this field in MyModel as mentioned in the bullet point you pointed here?
Yes. How you do it depends upon whether that default value is a known constant.
If it is, you can specify it as the default value in the form field definition. If it’s not, then you can initialize the value for that form field in the form’s __init__ method.
If it’s not, then you can initialize the value for that form field in the form’s __init__ method
Due the fact that value is not a known constant I set initial value to the field which works, however, I don’t know how to get rid of these -----.
Here is what I did
I don’t know if this is the best solution. For anyone with the same problem:
models.py:
class MyModel(models.Model):
field1 = models.ForeignKey(OtherModel, on_delete=models.CASCADE, blank=False, default="")
# default is not used, but needs to be set as KenWhitesell mentioned
forms.py:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ["field1"]
def __init__(self, condition=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if condition:
queryset = MyModel.objects.filter(field1=condition)
self.fields["field1"].queryset = queryset
if queryset:
self.fields["field1"].initial = queryset[0]