Django管理员内联表单,具有只读的旧值,并允许添加新的内联值 [英] Django admin inline form with readonly old values and allowing to add new inline values
问题描述
我正在尝试解决此问题,由于某种原因,到目前为止,每次尝试都失败了。我有两个简单的模型:问与答:
I am trying to figure this one out and for some reason every attempt failed so far. I have two simple models: Question and Answer:
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')时,由于消息文本区域为只读,因此我无法添加新答案。
For some reason I am unable to figure out what I am supposed to put into my admin.py to have previously added answers listed inline as readonly and at the same time allow inline new answers to be added. Everytime I set readonly_fields=('message') I am not able to add a new answer because the message textarea is readonly.
推荐答案
Ok, I understand what you want. To do so you can create a special widget which will show field value and at the same time will be a hidden input. Use this widget for previous answers:
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
这篇关于Django管理员内联表单,具有只读的旧值,并允许添加新的内联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!