我正在尝试使用django向一个bug跟踪应用程序添加一个注释组件。我有一个用于注释的文本字段和一个by字段--由用户id自动传播。
我希望注释文本字段在有人保存注释后变为只读。我尝试过几种方法。到目前为止,我想出的最好方法是将注释模型传递给ModelForm,然后使用表单小部件属性将字段转换为只读。
models.py
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('ticket', 'submitted_date', 'modified_date')
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.id:
self.fields['comments'].widget.attrs['readonly'] = True
class Comment(models.Model):
ticket = models.ForeignKey(Ticket)
by = models.ForeignKey(User, null=True, blank=True, related_name="by")
comments = models.TextField(null=True, blank=True)
submitted_date = models.DateField(auto_now_add=True)
modified_date = models.DateField(auto_now=True)
class Admin:
list_display = ('comments', 'by',
'submitted_date', 'modified_date')
list_filter = ('submitted_date', 'by',)
search_fields = ('comments', 'by',)
在bug跟踪程序中,我的评论模型与我的票据模型相关联。我将注释放在admin.py中的内联中,从而将注释连接到票据。现在问题变成了:如何将ModelForm传递到TabularInline中?TabularInline需要一个定义好的模型。然而,一旦我将一个模型传递到我的内联中,传递一个模型表单就变得毫无意义了。
admin.py
class CommentInline(admin.TabularInline):
model = Comment
form = CommentForm()
search_fields = ['by', ]
list_filter = ['by', ]
fields = ('comments', 'by')
readonly_fields=('by',)
extra = 1
有谁知道如何在不让常规模型的字段覆盖ModelForm的情况下将ModelForm传递到TabularInline中?提前感谢!
发布于 2011-03-22 16:08:38
不要在TabularInline子类中实例化表单:
form = CommentForm
https://stackoverflow.com/questions/5393952
复制相似问题