1👍
Here is my solution:
class ProductsSetForm(forms.ModelForm):
class Meta:
model = Group
exclude = []
products = forms.ModelMultipleChoiceField(
queryset=ProductsInstance.objects.all(),
required=False,
widget=FilteredSelectMultiple('products', False)
)
def __init__(self, *args, **kwargs):
super(ProductsSetForm, self).__init__(*args, **kwargs)
if self.instance.pk:
self.fields['products'].initial = self.instance.products_set.all()
def save_m2m(self):
self.instance.products_set.set(self.cleaned_data['products'])
def save(self, *args, **kwargs):
self.total_amount = sum(product.price_for_client for product in self.products_set.all())
instance = super(ProductsSetForm, self).save()
self.save_m2m()
return instance
class ProductsSetAdmin(admin.ModelAdmin):
form = ProductsSetForm
list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount')
fields = ['id', 'name', 'products_set','products', 'created_date', 'borrower', 'status', 'total_amount']
list_filter = ['borrower','created_date','status']
admin.site.register(ProductsSet, ProductsSetAdmin)
👤AdDa
0👍
You list the relation in the filter_horizontal
attribute [Django-doc]:
@admin.register(ProductsSet)
class ProductsSetAdmin(admin.ModelAdmin):
list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount')
fields = [
'id',
'name',
'products_set',
'created_date',
'borrower',
'status',
'total_amount',
]
filter_horizontal = ['products_set']
list_filter = ['borrower', 'created_date', 'status']
You can also use filter_vertical
attribute [Django-doc] where the two boxes appear above and below each other.
- [Answered ]-Django annotation and filtering
- [Answered ]-Django rest framework add field in serializer for using with post method only
- [Answered ]-Using Bootstrap to style Django Admin Panel
Source:stackexchange.com