Parsa
Parsa

Reputation: 151

How should i auto fill a field and make it readonly in django?

I`m new to django and i was doing a test for my knowledge.

Found a lot of duplicates in here and web but nothing useful

I'm trying to make a ForeignKey field which gets filled due to the other fields that user fills, and make it unchangeable for the user.

I thought that I should use overriding save() method but couldn't figure that at all.

How should I do that auto-fill and read-only thing?

Upvotes: 0

Views: 321

Answers (1)

hendrikschneider
hendrikschneider

Reputation: 1846

Your approach is right. Override the save method and if self.pk is not None raise an exception if your field has changed. You can use django model utils to easily track changes in your model: https://django-model-utils.readthedocs.io/en/latest/utilities.html#field-tracker

Principle:

class MyModel(models.Model):
    #....
    some_field = models.Foreignkey(...)
    tracker = FieldTracker()

    def save(*args, **kwargs):
        if self.pk is None:
            # new object is being created
            self.some_field = SomeForeignKeyObject
        else:
            if self.tracker.has_changed("some_field"):
                raise Exception("Change is not allowed")
        super().save(*args, **kwargs)

Upvotes: 1

Related Questions