'Django Admin Editable but Hidden field

Currently I have an editable field in a model in Django Admin. I would like this to remain editable, but not readable. For example, it would look like a password field with asterisks that an admin can change, but not read. How can I do this?



Solution 1:[1]

You could modify the str method to hide inputs using asterisks (or whichever character you choose), then replace the default admin input form with a ModelForm that uses PasswordInput widget for the fields.

from django.db import models
from django.contrib import admin
from django import forms

# The model (with sample fields)
class Test(models.Model):
    name = models.CharField(max_length=244, blank=False)
    date_joined = models.DateField(auto_now_add=True)
    job_title = models.CharField(max_length=255, blank=True)

    def __str__(self) -> str:
        display_name = '*' * len(self.name)
        display_date_joined = '*' * len(str(self.date_joined))
        display_job_title = '*' * len(self.job_title)
        return f"{display_name} - {display_date_joined} - {display_job_title}"

# The form class
class TestAdminForm(forms.ModelForm):
    class Meta:
        model = Test
        widgets = {
            'name': forms.PasswordInput,
            'job_title': forms.PasswordInput,
        }
        fields = '__all__'

# admin form class   
class TestAdmin(admin.ModelAdmin):
    form = TestAdminForm

# register site in Admin
admin.site.register(Test, TestAdmin)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hillary Vulimu