Как создать «Массовое редактирование» в Django?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как создать «Массовое редактирование» в Django?

Сообщение Anonymous »

Я хотел бы внести массовые изменения в свое приложение Django, но проблема в том, что эта функция не работает. В какой-то момент я заблудился при его создании и не знаю, что делаю не так. Я чувствую себя разбитым в этот момент, я не вижу других вариантов. Вот что я сделал до сих пор (я использую airtable в качестве базы данных):
Ошибка в основном возникает, когда он пытается получить продукты из таблиц после того, как они были выбраны с помощью флажка ( Я пытался его отладить и изменить, но не вижу, что еще можно сделать)
models.py
from django.db import models

class RC(models.Model):
sku = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
weight = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return self.name

class Category(models.Model):
sku = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=255)
category = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return self.name

class LB(models.Model):
sku = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=255)
cost = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return self.name

class PM(models.Model):
sku = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=255)
cost = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return self.name


views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .models import RC, LB, PM, Category
from django.http import HttpResponse
from django.contrib import messages
from pyairtable import Table
from django.core.exceptions import ObjectDoesNotExist

API_KEY = My airtable api
BASE_ID = My airtable app id

RC_table = Table(API_KEY, BASE_ID, 'RC')
LB_table = Table(API_KEY, BASE_ID, 'L&B')
PM_table = Table(API_KEY, BASE_ID, 'PM')
Category_table = Table(API_KEY, BASE_ID, 'Category')

def product_list(request):
rc_products = RC_table.all()
lb_products = LB_table.all()
pm_products = PM_table.all()
category_data = Category_table.all()

category_dict = {category['fields'].get('Name', 'Unknown'): category['fields'].get('Category', 'Undefined')
for category in category_data}

combined_products = []

table_filter = request.GET.get('table_filter', 'all')

for record in rc_products:
fields = record['fields']
category = category_dict.get(fields.get('Name', ''), 'N/A')
combined_products.append({
'id': record['id'],
'sku': fields.get('SKU', ''),
'name': fields.get('Name', ''),
'cost': fields.get('Cost', 0),
'price': fields.get('Price', 0),
'weight': fields.get('Weight (Lbs)', 0),
'profit': fields.get('Profit', 0),
'margin': fields.get('Margin', 0),
'category': category,
'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', ''),
'cost': fields.get('Cost', 0),
'price': None, # L&B does not have a Price field
'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', ''),
'cost': fields.get('Cost', 0),
'price': None, # PM does not have a Price field
'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)

def bulk_edit_products(request):
if request.method == 'POST':

selected_ids = request.POST.getlist('selected_products')

print(f"Selected product IDs for bulk edit: {selected_ids}")

if not selected_ids:
return HttpResponse("No products selected for bulk edit.", status=400)

products = []
for product_id in selected_ids:
product = None
print(f"Looking for product with sku: '{product_id}'")

for model, table_name_in_code in [(RC, 'RenoCart'), (LB, 'L&B'), (PM, 'Pont-Masson')]:
try:
product = model.objects.get(sku=product_id)
print(f"Found product: '{product.name}' in {table_name_in_code}")
product.table_name = table_name_in_code
products.append(product)
break
except ObjectDoesNotExist:
print(f"Product with sku '{product_id}' not found in {table_name_in_code}")
continue

if not products:
return HttpResponse("No valid products found for bulk edit.", status=400)

context = {
'products': products,
}

return render(request, 'inventory/bulk_edit_products.html', context)

selected_ids = request.GET.getlist('selected_products')
if not selected_ids:
return HttpResponse("No products selected for bulk edit.", status=400)

products = []
for product_id in selected_ids:
print(f"Looking for product with sku: '{product_id}'")

product = None
for model, table_name in [(RC, 'RenoCart'), (LB, 'L&B'), (PM, 'Pont-Masson')]:
try:
product = model.objects.get(sku=product_id)
print(f"Found product: '{product.name}' in {table_name}")
product.table_name = table_name
products.append(product)
break
except ObjectDoesNotExist:
print(f"Product with sku '{product_id}' not found in {table_name}")
continue

if not products:
return HttpResponse("No valid products found for bulk edit.", status=400)

context = {
'products': products,
}

return render(request, 'inventory/bulk_edit_products.html', context)


bulk_edit_products.html
{% block content %}
Bulk Edit Products


{% csrf_token %}



SKU
Name
Cost
Price
Weight (Lbs)



{% for product in products %}



{% if product.table_name == 'RenoCart' %}

{% else %}

{% endif %}




{% if product.table_name == 'RenoCart' %}

{% else %}

{% endif %}


{% if product.table_name == 'RenoCart' %}

{% else %}

{% endif %}


{% if product.table_name == 'RenoCart' %}

{% else %}

{% endif %}

{% endfor %}



Save Changes

{% endblock %}


products_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




Toggle Category



{% csrf_token %}
Bulk Edit



Select
SKU
Name
Cost
Price
Profit
Margin
Weight (Lbs)
Category
Store
Actions



{% for product in products %}


{{ product.sku }}
{{ product.name }}

{% if product.cost %}
${{ product.cost|floatformat:2 }}
{% else %}
N/A
{% endif %}


{% if product.price %}
${{ product.price|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.category|safe }}
{{ product.table_name }}

Edit |
Delete


document.addEventListener("DOMContentLoaded", function () {
const toggleButton = document.getElementById("toggle-category");
const categoryHeader = document.querySelector(".category-column");
const categoryCells = document.querySelectorAll("td.category-column");

toggleButton.addEventListener("click", function () {
// Check current display state
const isHidden = categoryHeader.style.display === "none";

// Toggle header and cells
categoryHeader.style.display = isHidden ? "" : "none";
categoryCells.forEach(cell => {
cell.style.display = isHidden ? "" : "none";
});

// Update button text
toggleButton.textContent = isHidden ? "Hide Category" : "Show Category";
});

// Initialize column as hidden
categoryHeader.style.display = "none";
categoryCells.forEach(cell => (cell.style.display = "none"));
toggleButton.textContent = "Show Category";
});


{% endfor %}





function confirmDelete(productId, table) {
if (confirm('Are you sure you want to delete this product?')) {
window.location.href = `/products/delete/${productId}/${table}/`;
}
}


{% endblock %}


Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-django
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Массовое редактирование страниц Elementor для удаления/редактирования чего-либо (контейнера/виджета)
    Anonymous » » в форуме Php
    0 Ответы
    13 Просмотры
    Последнее сообщение Anonymous
  • Массовое создание и редактирование вариантов Woocommerce
    Anonymous » » в форуме Php
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • Почему массовое выделение строк приводит к увеличению использования памяти
    Гость » » в форуме C++
    0 Ответы
    79 Просмотры
    Последнее сообщение Гость
  • Массовое обновление таймсерий C# MongoDB с добавлением повторяющихся записей
    Гость » » в форуме C#
    0 Ответы
    31 Просмотры
    Последнее сообщение Гость
  • Как разрешить массовое назначение API в веб-методе, имеющем один параметр?
    Anonymous » » в форуме C#
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»