Django管理内联表单具有只读旧值并允许添加新的内联值

时间:2015-01-15 03:50:06

标签: django django-admin

我正试图弄清楚这一点,并且由于某种原因,到目前为止每次尝试都失败了。我有两个简单的模型:问题和答案:

class Question(models.Model):
    phoneID = models.CharField(max_length=255, editable=False)
    name = models.CharField(max_length=255, editable=False)
    phone = models.CharField(max_length=255, editable=False)
    message = models.TextField(editable=False)
    answered = models.DateTimeField(editable=False)
    created = models.DateTimeField(auto_now_add=True, default=datetime.utcnow())

class Answer(models.Model):
    question = models.ForeignKey(Question)
    message = models.TextField()
    created = models.DateTimeField(auto_now_add=True, default=datetime.utcnow())

由于某些原因,我无法弄清楚我应该将什么放入我的admin.py,以便之前添加的内联列表以只读方式添加,同时允许添加内联新答案。每次我设置readonly_fields =('message')我都无法添加新的答案,因为消息textarea是readonly。

3 个答案:

答案 0 :(得分:4)

好的,我明白你想要什么。为此,您可以创建一个特殊的小部件,它将显示字段值,同时将是一个隐藏的输入。使用此小部件可获得先前的答案:

from django.forms.widgets import Widget
from django.forms.utils import flatatt
from django.utils.html import format_html

class ReadOnlyInput(Widget):

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type='hidden',
                                       name=name, value=value)
        return format_html('<input{} />{}', flatatt(final_attrs), value)


class AnswerForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AnswerForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['message'].widget = ReadOnlyInput()


class AnswerInline(admin.TabularInline):
    form = AnswerForm
    model = Answer

答案 1 :(得分:0)

Django 1.7允许您在admin inline中显示对象的属性。

class AnswerInline(admin.TabularInline):
    model = Answer
    fields = ('message', 'message_display', )
    readonly_fields=('message_display', )

    def message_display(self, obj):
        return obj.message

答案 2 :(得分:0)

今天有同样的问题。首先是尝试修改form,然后是get_readonly_fields,然后是其他许多东西。然后想起了这个优雅的东西:

class MyInline(admin.StackedInline):
    def has_change_permission(self, request, obj=None):
        return False