0

I need to manually add an entry to the database via the admin panel, but the admin should not be able to set all the values:

#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}

Admin should be able to create a Product and give it a name and price, but the status value should be set to 0. I already tried this approach and this, but no success.

I tried:

  1. Using an __init__ method to add initial values
  2. get_changeform_initial_data() method to add a status.

I always end up with sqlite3.IntegrityError: NOT NULL constraint failed: _TEST_Product.status.

edit: I know this can be done by setting a default value in the model, but this is not what I am looking for - I want to set this in the admin.

xtlc
  • 1,070
  • 1
  • 15
  • 41

1 Answers1

2

Edit

Since you don't want to use the default field, you should try this approach from 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)

Why don't you just use the default field?

status = models.PositiveIntegerField("status", default=0)
phyominh
  • 266
  • 1
  • 7
  • I made an edit for my post, I do not want to use the default setting in the model. I know this is a valid option. – xtlc Feb 18 '21 at 17:31
  • You sir, just solved a headache for me. Thank you very much! can I motivate you to take a look at [my other django-admin headache](https://stackoverflow.com/questions/65616204/django-admin-method-returns-multiple-instances-instead-of-one?noredirect=1#comment116012327_65616204) as well? – xtlc Feb 19 '21 at 08:08