Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: make field editable in add but not edit

I've got a model similar to this:

class Product(models.Model):     third_party_id = models.CharField(max_length=64, blank=False, unique=True) 

that uses the Django default primary key. I want users to be able to add products by setting the third_party_id on the add page, but I don't want that field editable in the edit page to avoid corrupting the third_party_id. In the Django docs, the same settings appear to be used for add and edit. Is this possible?

like image 275
Phil Loden Avatar asked Oct 22 '11 15:10

Phil Loden


People also ask

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

editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm.

How do you make a field optional in Django?

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.

How do I override a Django form?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

Is Django admin customizable?

The Django admin is a powerful built-in tool giving you the ability to create, update, and delete objects in your database using a web interface. You can customize the Django admin to do almost anything you want.


2 Answers

Do not set self.readonly_fields to avoid thread issues. Instead override get_readonly_fields method:

def get_readonly_fields(self, request, obj=None):     if obj: # obj is not None, so this is an edit         return ['third_party_id',] # Return a list or tuple of readonly fields' names     else: # This is an addition         return [] 
like image 71
shanyu Avatar answered Sep 18 '22 01:09

shanyu


The above is helpful (shanyu's answer using get_readonly_fields), however it does not work properly if used in "StackedInline". The result is two copies of whatever field is marked readonly, and it is not editable in the "add" instance. See this bug: https://code.djangoproject.com/ticket/15602

Hope this saves someone some searching!

like image 33
Jenni Avatar answered Sep 20 '22 01:09

Jenni