2017-08-09 54 views
2

这里是我的模型无法编辑,但可以在Django管理增加新的在线

class Note(): 
    note = models.TextField(null=False, blank=False, editable=True) 
    user = models.ForeignKey(to=User, null=True, blank=True) 

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) 
    object_id = models.PositiveIntegerField() 
    content_object = GenericForeignKey("content_type", "object_id") 

而且我创造了这个模型在任何管理纳入一个内嵌低于

class NoteInline(GenericTabularInline): 
    model = Note 
    extra = 0 

我需要什么这里是,我想看到所有当前的笔记,但不希望登录的用户编辑它们。此刻用户可以编辑旧的并添加新的。因此,这里是我做过什么,

class NoteInline(GenericTabularInline): 
    model = Note 
    extra = 0 

    def get_readonly_fields(self, request, obj=None): 
     if obj and 'change' in request.resolver_match.url_name: 
      return ['note', 'user', ] 
     else: 
      return [] 

但现在,如果用户增加了新的注释,他看到一个残疾(不可编辑)注释文本顷。但是用户可以看到旧字段不可编辑。

如何实现此功能?

+0

也许像这样的东西可以工作,为“添加”和“更改”视图添加了不同的内联? https://djangosnippets.org/snippets/3084/ – tdsymonds

+0

这不会使内联部分只读和部分可编辑(内联注释的新增内容)。所以这就是我所做的,分成两个新的内联。这里很好地解释了https://stackoverflow.com/a/28149575/1439913 –

回答

0

我有相同的查询。

但是,我不在乎内联字段是否为“只读”。我只是不希望他们一旦创建就改变了。

为此,我创建了forms.py其中提出了一个验证错误NoteForm如果情况发生了变化,同时它具有初始数据:

class NoteForm(forms.ModelForm): 
    def clean(self): 
     if self.has_changed() and self.initial: 
      raise ValidationError(
       'You cannot change this inline', 
       code='Forbidden' 
      ) 
     return super().clean() 

    class Meta(object): 
     model = Note 
     fields='__all__' 

admin.py:

class NoteInline(GenericTabularInline): 
    model = Note 
    extra = 0 
    form = NoteForm 
相关问题