2

I have the following Model definition:

def _createHashID():
    return uuid.uuid4().hex[:8] # 8 chars OK for < 100k items
class Act(models.Model):
    hashid = models.CharField(
    'hashid',
    max_length=20,
    default=_createHashID,
    unique=True,
    primary_key=True,
    help_text="technical identifier")

However, when I use the admin site to create an Act item, if the hashid value is readonly, a value is generated once when generating the form, and the value is re-generated when the Act object is saved. It means the Add an Act page will first present an identifier, say 583a95de, but we I hit save it will tell me:

The act "0b8c2832" was added successfully.

If if remove the readonly attribute of the admin.ModelAdmin object, the hashid is in an input (I obviously don't want that), but the proposed value if the real hashid of the new object.

How can I generate a readonly hashid the first time the object is instantiated (creation form) and make sure it really is the one used at save time?

The problem beyond that is I can't use inline formsets since the pk is changed at save time!

Zack4
  • 153
  • 1
  • 10

1 Answers1

1

You could override the form for the admin and the read only value on the form similar to this answer. https://stackoverflow.com/a/325038/1637351

Docs about admin's form.

As per the docs you'd set it like so:

class ActAdmin(admin.ModelAdmin):
    form = ActForm
Community
  • 1
  • 1
schillingt
  • 13,493
  • 2
  • 32
  • 34
  • Thanks Tim for this good answer, that could work. However this would allow the user to choose the hashid, since we can't control it hasn't been modified like in the question you link. Do you have an idea how to prevent that? – Zack4 Oct 30 '14 at 19:00
  • Simply put, you won't be able to. The value isn't being stored on the server. It'll only exist client-side. You could also have a hidden field that you could compare it against, but that can be changed as well. – schillingt Oct 30 '14 at 19:45