> On Mon, Jun 27, 2011 at 11:03 PM, momo2k <tkewolf@googlemail.com> wrote:
>> 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?
>
> 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
Ups, i forget something on this call:
super(MealModelForm, self).__init__(*args, **kwargs)
--
Marc
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment