简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM