Я пытаюсь добавить фильтры в панель поиска, но немного запутался. Мне бы хотелось, чтобы фильтры облегчали поиск в различных столбцах (например, «Артикул», «Название», «Стоимость», «Цена» и «Вес»). Как видите, у меня уже есть фильтр, и он идеален, поскольку фильтрует имена таблиц, из которых извлекается информация. У меня возникли проблемы с созданием фильтра панели поиска и прикреплением его к существующей панели поиска.
Я вставлю код для html и view.py:
product_list.html:
{% block content %}
Database
{% if user.is_authenticated %}
Logout
Add Product
{% endif %}
$(document).ready(function() {
$('#product-table').DataTable({
paging: true,
searching: true,
ordering: true,
info: true,
responsive: true,
pageLength: 25,
lengthMenu: [5, 10, 25, 50, 100]
});
});
All Stores
Pont-Masson
RenoCart
L&B
Filter
SKU
Name
Cost
Price
Profit
Margin
Weight (Lbs)
Store
Actions
{% for product in products %}
{{ product.sku }}
{{ product.name }}
{% if product.price %}
${{ product.price|floatformat:2 }}
{% else %}
N/A
{% endif %}
{% if product.cost %}
${{ product.cost|floatformat:2 }}
{% else %}
N/A
{% endif %}
{% if product.profit %}
${{ product.profit|floatformat:2 }}
{% else %}
N/A
{% endif %}
{% if product.margin %}
{{ product.margin|floatformat:2 }}%
{% else %}
N/A
{% endif %}
{% if product.weight %}
{{ product.weight|floatformat:2 }}
{% else %}
N/A
{% endif %}
{{ product.table_name }}
Edit |
Delete
{% endfor %}
function confirmDelete(productId, table) {
if (confirm('Are you sure you want to delete this product?')) {
window.location.href = `/products/delete/${productId}/${table}/`;
}
}
{% endblock %}
Views.py (только список товаров):
def product_list(request):
rc_products = RC_table.all()
lb_products = LB_table.all()
pm_products = PM_table.all()
combined_products = []
table_filter = request.GET.get('table_filter', 'all')
for record in rc_products:
fields = record['fields']
combined_products.append({
'id': record['id'],
'sku': fields.get('SKU', ''),
'name': fields.get('Name', ''),
'price': fields.get('Price', 0),
'cost': fields.get('Cost', 0),
'weight': fields.get('Weight (Lbs)', 0),
'profit': fields.get('Profit', 0),
'margin': fields.get('Margin', 0),
'table_name': 'RenoCart',
})
for record in lb_products:
fields = record['fields']
combined_products.append({
'id': record['id'],
'sku': fields.get('SKU', ''),
'name': fields.get('Name', ''),
'price': None, # L&B does not have a Price field
'cost': fields.get('Cost', 0),
'weight': None, # L&B does not have a Weight field
'table_name': 'L&B',
})
for record in pm_products:
fields = record['fields']
combined_products.append({
'id': record['id'],
'sku': fields.get('SKU', ''),
'name': fields.get('Name', ''),
'price': None, # PM does not have a Price field
'cost': fields.get('Cost', 0),
'weight': None, # PM does not have a Weight field
'table_name': 'Pont-Masson',
})
if table_filter == 'RenoCart':
combined_products = [product for product in combined_products if product['table_name'] == 'RenoCart']
elif table_filter == 'Pont-Masson':
combined_products = [product for product in combined_products if product['table_name'] == 'Pont-Masson']
elif table_filter == 'L&B':
combined_products = [product for product in combined_products if product['table_name'] == 'L&B']
else:
combined_products = combined_products
search_query = request.GET.get('search', '')
if search_query:
combined_products = [
product for product in combined_products
if search_query.lower() in product['name'].lower()
]
combined_products = sorted(combined_products, key=lambda x: x['name'], reverse=False)
context = {
'products': combined_products,
'search_query': search_query,
'table_filter': table_filter,
}
return render(request, 'inventory/product_list.html', context)
Подробнее здесь: https://stackoverflow.com/questions/792 ... -on-django
Как применить фильтры к панели поиска, созданной с помощью Datatables в Django? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как я могу цепорить фильтры с Django Filter и Django Autocomplete Light
Anonymous » » в форуме Python - 0 Ответы
- 13 Просмотры
-
Последнее сообщение Anonymous
-