【问题标题】:Django Admin: Give initial data to form fieldDjango Admin:将初始数据提供给表单字段
【发布时间】:2021-05-21 06:29:26
【问题描述】:

我需要通过管理面板手动向数据库添加一个条目,但管理员应该无法设置所有值:

#models.py
class Product(models.Model):
    price = models.DecimalField("price")
    status = models.PositiveIntegerField("status")
    name = models.CharField("name", max_length=31, unique=True)

## tried:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.initial['status'] = 2

#admin.py
class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ["price", "name",]

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    form = ProductForm

## tried:
    def get_changeform_initial_data(self, request):
        return {'status': 99}

管理员应该能够创建一个Product 并给它一个nameprice,但是status 的值应该设置为0。我已经尝试过this 方法和this,但没有成功。

我试过了:

  1. 使用__init__ 方法添加初始值
  2. get_changeform_initial_data() 方法添加状态。

我总是以sqlite3.IntegrityError: NOT NULL constraint failed: _TEST_Product.status结尾。

编辑:我知道这可以通过在模型中设置默认值来完成,但这不是我想要的 - 我想在管理员中设置它。

【问题讨论】:

  • 你为什么不简单设置status = models.PositiveIntegerField("status", default=0)
  • 我的示例过于简化,我已修复。我不想要默认字段。

标签: django django-forms django-admin


【解决方案1】:

编辑

由于您不想使用default 字段,您应该从this answer 尝试这种方法。

class ProductAdmin(admin.ModelAdmin):
    form = ProductForm

    def save_model(self, request, obj, form, change):
        obj.status = 0
        super().save_model(request, obj, form, change)

为什么不直接使用default 字段?

status = models.PositiveIntegerField("status", default=0)

【讨论】:

  • 我对我的帖子进行了编辑,我不想使用模型中的默认设置。我知道这是一个有效的选择。
  • 您先生,刚刚为我解决了一个头痛问题。非常感谢!我可以鼓励你看看my other django-admin headache吗?
猜你喜欢
  • 2010-12-25
  • 2013-05-05
  • 2012-06-03
  • 2013-09-11
  • 1970-01-01
  • 2012-09-21
  • 2021-01-08
  • 1970-01-01
相关资源
最近更新 更多