【问题标题】:Django admin: make field editable in add but not editDjango admin:使字段在添加中可编辑但不可编辑
【发布时间】:2011-12-13 05:18:49
【问题描述】:

我有一个类似的模型:

class Product(models.Model):
    third_party_id = models.CharField(max_length=64, blank=False, unique=True)

使用 Django 默认主键。我希望用户能够通过在添加页面上设置 third_party_id 来添加产品,但我不希望该字段在编辑页面中可编辑以避免损坏 third_party_id。在 Django 文档中,相同的设置似乎用于添加和编辑。这可能吗?

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    不要设置self.readonly_fields 以避免线程问题。而是覆盖 get_readonly_fields 方法:

    def get_readonly_fields(self, request, obj=None):
        if obj: # obj is not None, so this is an edit
            return ['third_party_id',] # Return a list or tuple of readonly fields' names
        else: # This is an addition
            return []
    

    【讨论】:

    • 很酷不知道这个方法。 +1。如果没有覆盖的方法,我们该怎么办?有什么策略吗?非常感谢。
    • @YUji,ModelAdmin 的 get_form 和 get_formset 方法几乎涵盖了所有用例。您可能需要查看代码 (options.py),在我为该主题寻找解决方案时,这些方法并未包含在文档中。
    • 如果没有方便的覆盖方法,我只是指一般的python。只是一个 lock.acquire()?
    • Python通过线程和多处理模块提供并发,可以看相关文档。但是,我真的怀疑它们是否应该在像管理员自定义这样微不足道的情况下使用。
    • 值得一提的是,这段代码必须进入 ModelAdmin 而不是 Model 本身
    【解决方案2】:

    以上内容很有帮助(shanyu 使用 get_readonly_fields 回答),但如果在“StackedInline”中使用,则无法正常工作。结果是标记为只读的任何字段的两个副本,并且在“添加”实例中不可编辑。看到这个错误:https://code.djangoproject.com/ticket/15602

    希望这可以节省一些搜索!

    【讨论】:

      【解决方案3】:

      我不确定这是否是最好的方法,但您可以为管理员定义自己的表单。并自定义验证您的third_party_id,如果已设置则拒绝:

      Admin.py

      class ProductAdminForm(forms.ModelForm):
          class Meta:
              model = Product
      
          def clean_third_party_id(self):
              cleaned_data = self.cleaned_data
              third_party_id = cleaned_data['third_party_id']
              id = cleaned_data['id']
              obj = Product.objects.get(id=id)
              if obj.third_party_id != third_party_id:
                  raise ValidationError("You cannot edit third_party_id, it must stay as %s" % obj.third_party_id)
               return third_party_id
      
      
      class ProductAdmin(admin.Admin):
          form = [ProductAdminForm,]
      

      【讨论】:

        猜你喜欢
        • 2015-05-21
        • 2012-11-07
        • 1970-01-01
        • 2014-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        相关资源
        最近更新 更多