1

I have two models named 'Message' and 'Ticket'. Message has a Foreignkey to Ticket. I showed Messages of a Ticket in django admin, using StackedInline. But the problem is I want that the already created messages be read-only, while being able to create new message, too.

I've also check bunch of questions; like this or this. But none of the was helpful! Or at least, I could not get the clue!

This is my code:

models.py:

class Ticket(models.Model):
    title = models.CharField(max_length=128)
    #...

class Message(models.Model):
    text = models.TextField()
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
    attachment = models.FileField(upload_to=some_url_pattern)
    sender = models.CharField(max_length=2, editable=False)

admin.py:

class MessageInline(admin.StackedInline):
    model = Message
    extra = 1

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ['text', 'attachment']
        else:
            return []


@admin.register(Ticket)
class ResponderAdmin(admin.ModelAdmin):
    fields = ['title']
    inlines = [MessageInline]

As can be seen, I tried to achieve the goal by overriding get_readonly_fields but this is what happend: the screenshot of admin page

As can be seen in the picture, every message inlines has been made read-only and I can not add a new message...

Can anyone help me with this issue?

Sepehr M
  • 33
  • 4

1 Answers1

0

I am assuming this is for admin.

Remove the user's SuperUser access but leave them with Staff access. Then use permissions to give them Add and access for the specific model but do not give them Update or Delete access. That should enable them to view the data without being able to change or delete it.

HenryM
  • 5,557
  • 7
  • 49
  • 105
  • Thanks for your answer but I assume you didn't understand the issue properly. It's not about giving permission to add a new 'Message'. I need to show existing messages in read-only mode and also be able add a new one; which I couldn't do, as shown in picture. – Sepehr M Apr 22 '19 at 17:53
  • Principle is the same - you give them view access but not add, update or delete – HenryM Apr 22 '19 at 17:58
  • The problem is I want to give them view and add at the same time... It's not related to permissions; It's more about the form that StackedInline uses for showing each inline... – Sepehr M Apr 22 '19 at 18:45
  • I've done it with permissions on sites in the past. You are welcome to take a different approach – HenryM Apr 22 '19 at 19:15
  • So, I have to create a specific 'staff' user. Anyway, you think nothing can be done for admin user? – Sepehr M Apr 23 '19 at 05:09
  • Admin is set as superuser so you've given them permissions for everything but you don't want them to have permissions for everything and the most simple way to deal with that is using permissions – HenryM Apr 23 '19 at 07:44