Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin make a field read-only when modifying obj but required when adding new obj

In admin I would like to disable a field when modifying object, but make it required when adding new object.

Whats the django way to go about this one?

like image 580
frnhr Avatar asked Dec 03 '10 08:12

frnhr


People also ask

How do you make a field readonly in Django admin?

Django admin by default shows all fields as editable and this fields option will display its data as-is and non-editable. we use readonly_fields is used without defining explicit ordering through ModelAdmin or ModelAdmin. fieldsets they will be added. Now we make the Question text fields read-only.

How do you make a field non mandatory in Django admin?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

How do I make a field optional in Django admin?

You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.


1 Answers

You can override the admin's get_readonly_fields method:

class MyModelAdmin(admin.ModelAdmin):      def get_readonly_fields(self, request, obj=None):         if obj: # editing an existing object             return self.readonly_fields + ('field1', 'field2')         return self.readonly_fields 
like image 53
Bernhard Vallant Avatar answered Sep 28 '22 05:09

Bernhard Vallant