Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django AdminForm field default value

Tags:

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?

like image 512
bartek Avatar asked May 28 '11 22:05

bartek


2 Answers

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 
like image 122
Paul Kenjora Avatar answered Nov 01 '22 19:11

Paul Kenjora


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.

like image 29
Wtower Avatar answered Nov 01 '22 19:11

Wtower