Advertisement
kastielspb

Prefilled admin inlines

Oct 26th, 2020 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. class ProductRegexpFormset(BaseInlineFormSet):
  2.     """
  3.    Prefilled formset
  4.    """
  5.  
  6.     def __init__(self, *args, **kwargs):
  7.         super().__init__(*args, **kwargs)
  8.         data = {item.shop_id: item.shop for item in self.queryset}
  9.         self.shops = Shop.objects.exclude(id__in=data.keys())
  10.         values = list(data.values())
  11.         values.extend(self.shops)
  12.         self.initial = [{'shop': shop} for shop in values]
  13.  
  14.  
  15. class ProductRegexpInline(admin.StackedInline):
  16.     """
  17.    Prefilled inilines with disabled dropdown
  18.    """
  19.     formset = ProductRegexpFormset
  20.     model = ProductRegexp
  21.     fields = ('shop', ('name_regexp_list', 'info'))
  22.  
  23.     def __init__(self, *args, **kwargs):
  24.         super().__init__(*args, **kwargs)
  25.         self.shop_count = Shop.objects.count()
  26.    
  27.     def get_min_num(self, request, obj=None, **kwargs):
  28.         return self.shop_count
  29.    
  30.     def get_max_num(self, request, obj=None, **kwargs):
  31.         return self.shop_count
  32.  
  33.     def get_extra(self, request, obj=None, **kwargs):
  34.         return self.shop_count
  35.  
  36.     def formfield_for_dbfield(self, db_field, **kwargs):
  37.         if db_field.name == 'shop':
  38.             field = db_field.formfield()
  39.             field.widget.attrs['style'] = 'pointer-events: none;'
  40.             return field
  41.         return super().formfield_for_dbfield(db_field, **kwargs)
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement