inf value in Django model FloatField

Hello,

I have a problem with displaying inf value inside a FloatField in Django admin interface. In the list overview the inf shows with no problem:

But when I go to edit page the field is blank for some reason:

The FloatField in Django doesn’t accept inf by default. Everytime I want to save an entity with inf value in Threshold high field, Django rejects it and saves None instead as if the inf doesn’t pass some internal Django validation.

Here is my model code:

class CropStageHasCondition(models.Model, GenericCheckForDelete):
    id = CompositeKey(columns=['crop_stage_id', 'condition_id'])
    crop_stage = models.ForeignKey(CropStage, models.DO_NOTHING)
    condition = models.ForeignKey(Condition, models.DO_NOTHING)
    threshold_low = models.FloatField(blank=True, null=True)
    threshold_high = models.FloatField(blank=True, null=True)
    threshold_mismatch_impact = models.ForeignKey('ThresholdMismatchImpact', models.DO_NOTHING, blank=True, null=True)
    health_threshold_low = models.FloatField(blank=True, null=True)
    health_threshold_high = models.FloatField(blank=True, null=True)
    health_threshold_mismatch_impact = models.ForeignKey('ThresholdMismatchImpact', models.DO_NOTHING, related_name='cropstagehascondition_health_threshold_mismatch_impact_set', blank=True, null=True)
    relevant_for_calculation = models.BooleanField()

    class Meta:
        managed = False
        db_table = 'planner"."crop_stage_has_condition'
        unique_together = (('crop_stage', 'condition'),)

    def clean(self):
        if self.threshold_high == None:
            self.threshold_high = float('inf')

    def __str__(self) -> str:
        return f"{self.crop_stage} - {self.condition}"

Thank you for any idea on how to solve this.

From the screenshot it looks like you’re trying to use an input tag with type="number". That’s not going to work in this case. You’d need to use type="text" for that value (inf) to be accepted as input. (You then may also need to write a custom validator for that field to accept that value in that field as input.)

Side note: In the general case, you want to define mixin class names before models.Model in the model definition.

Unless you specifically know that GenericCheckForDelete is designed to work this way, you’re better off writing this as:
class CropStageHasCondition(GenericCheckForDelete, models.Model):

Now, if GenericCheckForDelete is a descendant class of Model, and not just a mixin, then you don’t need to identify models.Model here and can just write:
class CropStageHasCondition(GenericCheckForDelete):

I guess I would need to create a custom template for that?

Not a template - a custom Form. (You can specify the widget to be used in a ModelForm using the widgets directive in the Meta class.) You would then identify this form class as the form to be used by the admin in your ModelAdmin class.

1 Like