Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Admin inline forms initial data for every instance

Tags:

I've been reading a lot but I don't seem to be able to figure out a solution to this.

I'm writing an application in Django, I'm still writing the admin side.

I have a model called "Environments" and a model called "Servers", there is a ForeignKey relation between Servers and Environments such as a given Environment has several servers.

When modifying the "add" form for Environments in the admin interface I use a Inline form to be able to visualize the list of Servers that will be associated to the Environment, something like this:

class ServerInline(admin.TabularInline):     model = Server     extra = 39  class EnvironmentAdmin(admin.ModelAdmin):     inlines = [ServerInline] 

Pretty simple right?

What I would like to do is prepopulate the Servers inline forms with default values, I've been able to prepopulate them with the same value doing this:

class ServerInlineAdminForm(forms.ModelForm):     class Meta:         model = Server      def __init__(self, *args, **kwargs):         super(ServerInlineAdminForm, self).__init__(*args, **kwargs)         self.initial['name']='Testing'  class ServerInline(admin.TabularInline):     form = ServerInlineAdminForm     model = Server     extra = 39  class EnvironmentAdmin(admin.ModelAdmin):     inlines = [ServerInline] 

But this isn't what I want, I would like to be able to initialize the 39 Server form instances with 39 different values that I have in a list. What would be the best way to do that??

Thank you!

like image 568
user1664820 Avatar asked Sep 12 '12 09:09

user1664820


1 Answers

Here is my implementation, thanks to Steven for the idea.

All in admin.py:

class SecondaryModelInline(admin.ModelAdmin):     model = SecondaryModel     formset = SecondaryModelInlineFormSet      def get_formset(self, request, obj=None, **kwargs):         formset = super(SecondaryModelInline, self).get_formset(request, obj, **kwargs)         formset.request = request         return formset      def get_extra(self, request, obj=None, **kwargs):         extra = super(SecondaryModelInline, self).get_extra(request, obj, **kwargs)         something = request.GET.get('something', None)         if something:             extra = ... figure out how much initial forms there are, from the request ...         return extra 

Someplace before, also in admin.py, this:

class SecondaryModelInlineFormSet(forms.models.BaseInlineFormSet):     model = SecondaryModel      def __init__(self, *args, **kwargs):         super(SecondaryModelInlineFormSet, self).__init__(*args, **kwargs)                     if self.request.GET.get('something', None):             # build your list using self.request             self.initial=[{'field_a': 'A', ...}, {}... ] 
like image 190
frnhr Avatar answered Sep 28 '22 04:09

frnhr