Django Read Only Fields ,if there is any value

Viewed 80

I wrote this code to make read only field, but i want to make an exception that if there is value then that row will only readonly , and if there is not any value the it will be editable,

In this picture i am saving checking tick marks after saving that become read only in the high light empty fields i do not want  readony

model.py

class Name(models.Model):
  name = models.BooleanField(default=False)
  id = models.BooleanField(default=False)

 def __str__(self):
    return f"{self.name}"

admin.py

class Name(admin.ModelAdmin):
model = models.Name
def get_readonly_fields(self, request, obj=None):
  if obj:
     return self.readonly_fields + ("name", "id")
  return self.readonly_fields
1 Answers

This is example how you can do two of three fields make readonly in admin panel.

models.py:

class Demo(models.Model):
    example_field_1 = models.CharField(max_length=1000)
    example_field_2 = models.CharField(max_length=1000)
    example_field_3 = models.CharField(max_length=1000)
    
    def __str__(self):
        return str(self.pk)

In admin.py:

from django.contrib import admin
from . models import Demo

@admin.register(Demo)
class DemoAdmin(admin.ModelAdmin):
    readonly_fields = ['example_field_1', 'example_field_2']
Related