I have a Django admin form. And now I want to fill it's initial field with data based on my model. So I tried this:
class OrderForm(forms.ModelForm): class Meta: model = Order email = CharField(initial="null", widget=Textarea(attrs={'rows': 30, 'cols': 100})) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) products = kwargs['instance'].products.all() self.message = purchase_message % ( "".join(["<li>" + p.name + ": " + str(p.price) + "</li>" for p in products]), reduce(lambda x, y:x + y.price, products, 0) ) # and here I have a message in self.message variable super(OrderForm, self).__init__(*args, **kwargs)
At this point i don't know how to access email field to set it's initial value before widget is rendered. How can i do this?
Assuming the value is based on 'request' you should use this:
class MyModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(MyModelAdmin, self).get_form(request, obj, **kwargs) form.base_fields['my_field_name'].initial = 'abcd' return form
Since Django 1.7 there is a function get_changeform_initial_data
in ModelAdmin that sets initial form values:
def get_changeform_initial_data(self, request): return {'name': 'custom_initial_value'}
EDIT: Apart from that, @Paul Kenjora's answer applies anyway, which might be useful if you already override get_form
.
In case of inline (InlineModelAdmin
) there is no get_changeform_initial_data
. You can override get_formset
and set formset.form.base_fields['my_field_name'].initial
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With