Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

django - Change to UUID as pk triggers form "non-editable field" error

I am experimenting with moving our project over to UUID field primary keys. I've created a branch, deleted all the migrations and the database, and am trying to makemigrations when I hit new errors.

Per the docs, I made id an explicit field in our site Abstract Base Class of Model:

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

I was surprised that this results in a new error for ModelForms where 'id' is included in the fields property. The error says:

```django.core.exceptions.FieldError: 'id' cannot be specified for Statement model form as it is a non-editable field```

I removed 'id' from one Form, but for others it seems pretty essential to the function of the form / formsets that the primary key be returned with POST data. The Django implicit 'id' integer autofield is not editable, yet we did not get this error before, and we still don't where fields = '__all__' is set.

question from:https://stackoverflow.com/questions/65932689/change-to-uuid-as-pk-triggers-form-non-editable-field-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you need to remove the non-editable field from your class form list of fields if relevant.

Then update your model admin to make your id as read_only:

class YourModelAdmin(admin.ModelAdmin):
    readonly_fields=('id',)
    form = YourModelModelForm # if relevant, otherwise keep the readonly_fields 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...