Reputation: 29536
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:
User
adminpath
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
Reputation: 1933
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
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