Reputation: 1368
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:
__init__
method to add initial valuesget_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.
Upvotes: 0
Views: 810
Reputation: 306
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)
Upvotes: 2