akonsu
akonsu

Reputation: 29536

auto-generate fields in inline admin

I have these (simplified) models:

class User(models.Model):
    email = models.EmailField(unique=True)

class Invitation(models.Model):
    user = models.ForeignKey(User)
    path = models.CharField(max_length=40, unique=True)

The path field in the Invitation table will contain a SHA1 hash that is going to be used as part of the URL to access the user's data.

I have this admin code:

class InvitationInline(admin.TabularInline):
    model = models.Invitation

class UserAdmin(admin.ModelAdmin):
    inlines = (InvitationInline,)

admin.site.register(models.User, UserAdmin)

this displays the user and adds a list of invitations at the bottom.

Since my path values in the Invitation table are going to be generated by SHA1 algorithm from the user's email and the current timestamp, I need to:

  1. have no empty 'Invitations' rows displayed by default in the User admin
  2. remove the edit field for path column from the admin, and have the path field automatically generated when the "add another invitation" button is clicked.

I have no idea how to achieve this, could someone help me?

Upvotes: 2

Views: 971

Answers (1)

Ivan Kharlamov
Ivan Kharlamov

Reputation: 1933

  1. To disable display of extra inline invitation forms just add extra = 0 attribute to your InvitationInline class:

    class InvitationInline(admin.TabularInline):
        fields = ('user',)
        extra = 0
        model = models.Invitation
    
  2. Probably, the best place to put the path generation is the save method of Invitation model:

    import hashlib
    import random
    
    class Invitation(models.Model):
        user = models.ForeignKey(User)
        path = models.CharField(max_length=40, unique=True)
    
        def save(self, *args, **kwargs):
            if self.pk is None:  # This is true only when the model has
                                 # never been saved to database.
                salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                self.path = hashlib.sha1(salt +\
                    str(self.user.email)).hexdigest()
    
            super(Invitation, self).save(*args, **kwargs)  
    

To remove path from InvitationInline just add fields attribute to it: fields = ('user',).

Upvotes: 1

Related Questions