Set initial value in fields Django Admin form


Sometimes we need to setup different initial data when user create new records in Django Admin.
Well, when you came at this page, I believe you already search through a lot of web pages and doesn’t see the solution, isn’t ? ๐Ÿ˜€

For instance, I have Order Model like this :

1
2
3
4
5
6
7
8
9
class OrderInfo(CommonInfo):
    """Order to pay subscription"""
    amount = models.DecimalField(max_digits=10,decimal_places=2,
                                 default=SUBSCRIBE_AMOUNT)
    currency = models.ForeignKey(Currency, related_name="%(class)s_currency")
    payment_status = models.ForeignKey(
                         PaymentStatus,
                         related_name="%s(class)s_payment_status"
                     )

And here is admin.py :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class OrderAdmin(admin.ModelAdmin):
    list_display = [‘id’, ‘amount’, ‘currency’, ‘payment_status’]

    def get_object(self, request, object_id):
        obj = super(OrderAdmin, self).get_object(request, object_id)
        if obj is not None:
            obj.amount = Decimal("0")
        return obj

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == ‘currency’:
            kwargs["queryset"] = Currency.objects.get(code="USD")
        return super(OrderAdmin, self).formfield_for_foreignkey(db_field,
                                                                request,
                                                                **kwargs)

You will see there are two kinds of function here :
1. get_object(self, request, object_id)
This function used for set initial value for non-foreignKey fields.

2.formfield_for_foreignkey(self, db_field, request, **kwargs)
This function used for set initial value for ForeignKey fields.

Easy right? ๐Ÿ˜€


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.