Hi. I am asking this question after reading the following questions: Question_1 and Question_2. Question_1 doesn't have any appropriate answers and Question_2 is having an alternative solution but not a perfect solution.
Here I have two models and admins for them.
models.py
class TaskList(models.Model):
task_name = models.CharField(max_length = 255, unique = True)
description = models.TextField()
assignee_role = models.ForeignKey(Group, related_name = "assignee_roles")
assignee_name = models.ForeignKey(User, related_name = "assignee_names")
def __unicode__(self):
return "%s" % (self.task_name)
class TaskComments(models.Model):
tasklist = models.ForeignKey(TaskList)
time = models.DateTimeField(null = True, blank = True)
comment = models.TextField()
def __unicode__(self):
return ""
def save(self, *args, **kwargs):
self.time = datetime.datetime.now()
super(TaskComments, self).save(*args, **kwargs)
admin.py
class TaskCommentsInlineAdmin(admin.TabularInline):
model = TaskComments
can_delete = False
class TaskListAdmin(admin.ModelAdmin):
inlines = [TaskCommentsInlineAdmin, ]
def add_view(self, request, form_url = '', extra_context = None):
self.readonly_fields = ()
return super(TaskListAdmin, self).add_view(request, form_url, extra_context)
def change_view(self, request, form_url = '', extra_context = None):
self.readonly_fields = ('task_name', 'description', )
return super(TaskListAdmin, self).change_view(request, form_url, extra_context)
Here the model TaskComments is being used as inline in TaskList.
SCENARIO 1
Here what I want to achieve is:
When Adding task comments
- Hide the field "time" and update it in backend.
- Able to type "comments" and save.
When opening after saving comments
- Both "Time" and "Comments" field should be visible and readonly for already added comments.
- Able to add new comments as described above.
SCENARIO 2
- Same as previous scenario.
- The only addition is, the comment should be editable for the user who added it and readonly for all other users. (I can update and get the user who adds the comment).
These are the things I would like to achieve. I have tried using add_view and change_view in admin. But they are not working for inline. Please provide a solution to achieve these things. Thanks in advance.