Я пытаюсь добавить фильтры в панель поиска, но немного запутался. Мне бы хотелось, чтобы фильтры облегчали поиск в различных столбцах (например, «Артикул», «Название», «Стоимость», «Цена» и «Вес»). Как видите, у меня уже есть фильтр, и он идеален, поскольку фильтрует имена таблиц, из которых извлекается информация. У меня возникли проблемы с созданием фильтра панели поиска и прикреплением его к существующей панели поиска.
Я вставлю код для 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
Программы на Python
1733156038
Anonymous
Я пытаюсь добавить фильтры в панель поиска, но немного запутался. Мне бы хотелось, чтобы фильтры облегчали поиск в различных столбцах (например, «Артикул», «Название», «Стоимость», «Цена» и «Вес»). Как видите, у меня уже есть фильтр, и он идеален, поскольку фильтрует имена таблиц, из которых извлекается информация. У меня возникли проблемы с созданием фильтра панели поиска и прикреплением его к существующей панели поиска.
Я вставлю код для html и view.py:
product_list.html:
{% block content %}
Database
{% if user.is_authenticated %}
[url={% url ]
Logout
[/url]
[url={% url ]Add Product[/url]
{% 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 }}
[url={% url ]Edit[/url] |
[url={% url ]Delete[/url]
{% 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)
Подробнее здесь: [url]https://stackoverflow.com/questions/79244704/how-to-apply-filters-to-searchbar-generated-with-datatables-on-django[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия