ModelAdmin, custom field: default value?

1,946 views
Skip to first unread message

momo2k

unread,
Jun 27, 2011, 5:03:57 PM6/27/11
to Django users
Hello,

Is there a way to set dynamic default values for custom fields in the
admin?

Description of the problem:

# models.py
# there are two models
class Meal(models.Model):
name = ...

def check_new_price(self, price):
# checks if the price is new and creates a new price if
neccessary

class Price(models.Model):
meal = models.ForeignKey(Meal, ....)
valid_to = models.DateField(....) # None for current price
amount = CurrencyField() # nearly identical to IntegerField

# admin.py
# I extended the Admin with a custom form:
class MealModelForm(forms.ModelForm):
price = CurrencyFormField() # Nearly identical to Decimalfield
class Meta:
model = Meal

class MealAdmin(admin.ModelAdmin):
form = MealModelForm
....
def save_model(self, request, obj, form, change):
super(MealAdmin, self).save_model(request, obj, form, change)
obj.check_new_price(form.cleaned_data['price'])


My question is: How do i tell the django admin to display the current
price in the form field? I already tried to add an "price"-attribute
in the ModelAdmin.get_object() method, but that doesn't work. If I
call the Admin page for a meal, the price is blank instead of
displaying the current price.

So, repeating my first question: Is there a way to set dynamic default
values for custom fields in the admin?

Marc Aymerich

unread,
Jun 28, 2011, 4:27:47 AM6/28/11
to django...@googlegroups.com

Yes, and it should be done on the __init__ method of your custom form.


class MealModelForm(forms.ModelForm):
price = CurrencyFormField() # Nearly identical to Decimalfield
class Meta:
model = Meal

def __init__(self, *args, **kwargs):
super(MealModelForm).__init__(*args, **kwargs)
if 'instance' in kwargs.keys():
self.fields['price'].initial =
Price.objects.get(meal=kwargs['instance']).amount

--
Marc

Marc Aymerich

unread,
Jun 28, 2011, 4:31:59 AM6/28/11
to django...@googlegroups.com

Ups, i forget something on this call:
super(MealModelForm, self).__init__(*args, **kwargs)

--
Marc

momo2k

unread,
Jun 28, 2011, 7:15:00 AM6/28/11
to Django users
Thanks, working :)

def __init__(self, *args, **kwargs):
super(MealModelForm, self).__init__(*args, **kwargs)
try:
instance = kwargs['instance']
self.fields['price'].initial = instance.price()
except (KeyError, AttributeError):
pass
Reply all
Reply to author
Forward
0 new messages