Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8093263
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T20:28:02+00:00 2026-06-05T20:28:02+00:00

I have an admin model with a few inline models included with it (see

  • 0

I have an admin model with a few inline models included with it (see the ResourceUserAdmin model below for full class):

    inlines = [ 
            ResourceLocationInlineAdmin ,
            ResourceCategoryInlineAdmin , 
            ResourceStageInlineAdmin ,
          ]

When a user clicks to create a new ResourceUserAdmin I want the inlines of the class ResourceCategoryInlineAdmin to get initial values — note that these relationships will not be saved to the database. I’ve tried to override parts of the add_view function to get what i want but I can’t figure out how to pass multiple inline forms back to parent.

Any ideas on how to achieve this?

Models

class ResourceUserAdmin( admin.ModelAdmin ):
    inlines = [ 
            ResourceLocationInlineAdmin ,
            ResourceCategoryInlineAdmin , 
            ResourceStageInlineAdmin ,
          ]

    list_display = ( 
                 'user' , 
                 'name' ,
                 'state' ,
                 'email' ,
                 'website' ,
                 'phone' ,
                 'logo_url_link',
    )

    search_fields = ( 'name' , 'email' , 'website'  )

    list_filter = ( 'name' , 'state' , 'email' , 'website' )

    ordering = ( 'name', )

     fields = ( 
             'user' , 
             'name' ,
             'state' ,
             'email' ,
             'website' ,
             'phone' ,
             'logo' ,
             'ideal_candidate',
    )
admin.site.register( ResourceUser, ResourceUserAdmin )

Here is the inline model I want to create many by default:

class ResourceCategoryInlineAdmin( admin.StackedInline ):
    model = ResourceCategory
    extra = 0

class ResourceCategoryAdmin( admin.ModelAdmin ):
    list_display = ( 'user' ,
                     'category' , )

    ordering = ( 'user' , )
    fields = ( 'user' , 'category' )

    def formfield_for_foreignkey( self, db_field, *args, **kwargs ):
        if isinstance( db_field, models.ForeignKey ):
            if db_field.name == 'category':
                kwargs['widget'] = forms.RadioSelect()
        return super( ResourceCategoryAdmin, self).formfield_for_foreignkey( db_field, **kwargs )

admin.site.register( ResourceCategory, ResourceCategoryAdmin )
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T20:28:03+00:00Added an answer on June 5, 2026 at 8:28 pm

    This is one solution, though not the option i really wanted to use. You can do it by overriding the the whole add_view function and setting the intial attributes for each form in the formsets (look for the override comment below)

    def add_view(self, request, form_url='', extra_context=None):
        "The 'add' admin view for this model."
        model = self.model
        opts = model._meta
    
        if not self.has_add_permission(request):
            raise PermissionDenied
    
        ModelForm = self.get_form(request)
        formsets = []
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request), self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST, files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix, queryset=inline.queryset(request))
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=False)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=False)
    
                self.log_addition(request, new_object)
                return self.response_add(request, new_object)
        else:
            # Prepare the dict of initial data from the request.
            # We have to special-case M2Ms as a list of comma-separated PKs.
            initial = dict(request.GET.items())
            for k in initial:
                logger.info( "for k in initial, k = %s" % k )
                try:
                    f = opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            form = ModelForm(initial=initial)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
    
                formset = FormSet(instance=self.model(), prefix=prefix, queryset=inline.queryset(request))
    
                #
                #
                # override the inlines of my choice
                # to create initial values
                #
                #
                if inline.__class__.__name__ == 'ResourceCategoryInlineAdmin':
                    for frm, category in zip( formset, Category.objects.all() ):
                       frm.fields['category'].initial = category
    
                formsets.append(formset)
    
        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
            self.prepopulated_fields, self.get_readonly_fields(request),
            model_admin=self)
        media = self.media + adminForm.media
    
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
                fieldsets, readonly, model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
    
        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, form_url=form_url, add=True)
        #return super(ResourceUserAdmin, self).add_view(request, form_url=form_url, extra_context=extra_context)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have few similar models in Django: class Material(models.Model): title = models.CharField(max_length=255) class Meta:
If I have a models.py like class WidgetType(models.Model): name = models.CharField(max_length=200) class Widget(models.Model): typeid
Thanks in advance...see below the code.. i have 2 models, category and product my
I have a very basic Admin model: class Admin < ActiveRecord::Base has_secure_password validates_uniqueness_of :email
I have a few checkboxes coming from nested model ( :admin accepts_nested_attributes_for :account_setting ).
I have a model: class picture(models.Model): name = models.CharField(null=False, blank=False, max_length=128) collections = models.ManyToManyField('collection',
I have namespaced model Equipment::Feature and namespaced controller in my admin part Admin::Equipment::FeaturesController .
I have a model name called StoreEntry. Django admin changes it to look like
I have two models User and Admin(with RailsAdmin) that use Devise. I sign in
I have an admin view which contains four foreign keys each with a few

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.