fix: Исправить сохранение приоритетов товаров в группе вариантов
Проблема: при перемещении товаров стрелками вверх/вниз приоритеты изменялись только в UI, но при сохранении их значения не обновлялись в БД и возвращались в исходное состояние. Причина: после сохранения формсета в view.form_valid() вызывалась функция _recalculate_priorities(), которая перезаписывала все приоритеты по ID товаров, игнорируя значения из формсета. Решение: 1. Удалена функция _recalculate_priorities() которая перезаписывала приоритеты 2. Теперь приоритеты сохраняются напрямую из формсета (inlineformset содержит поле 'priority') 3. Улучшен JavaScript селектор в updatePriorities() для более надёжного нахождения поля priority 4. Добавлено логирование в консоль для отладки (console.log) Теперь при перемещении товаров стрелками и нажатии "Сохранить" приоритеты правильно сохраняются в БД. 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -293,9 +293,17 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
let priority = 1;
|
let priority = 1;
|
||||||
container.querySelectorAll('.item-row:not([style*="display: none"])').forEach(row => {
|
container.querySelectorAll('.item-row:not([style*="display: none"])').forEach(row => {
|
||||||
const priorityCell = row.querySelector('.item-priority');
|
const priorityCell = row.querySelector('.item-priority');
|
||||||
const priorityInput = row.querySelector('[name$="-priority"]');
|
const priorityInput = row.querySelector('input[name$="-priority"]');
|
||||||
if (priorityCell) priorityCell.textContent = priority;
|
|
||||||
if (priorityInput) priorityInput.value = priority;
|
if (priorityCell) {
|
||||||
|
priorityCell.textContent = priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (priorityInput) {
|
||||||
|
priorityInput.value = priority;
|
||||||
|
console.log(`Обновлено поле приоритета: ${priorityInput.name} = ${priority}`);
|
||||||
|
}
|
||||||
|
|
||||||
priority++;
|
priority++;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -170,11 +170,9 @@ class ProductVariantGroupUpdateView(LoginRequiredMixin, UpdateView):
|
|||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
self.object = form.save(commit=True)
|
self.object = form.save(commit=True)
|
||||||
items_formset.instance = self.object
|
items_formset.instance = self.object
|
||||||
|
# Сохраняем формсет, который содержит приоритеты установленные пользователем
|
||||||
items_formset.save()
|
items_formset.save()
|
||||||
|
|
||||||
# Пересчитываем приоритеты после редактирования
|
|
||||||
self._recalculate_priorities(self.object)
|
|
||||||
|
|
||||||
messages.success(
|
messages.success(
|
||||||
self.request,
|
self.request,
|
||||||
f'Группа вариантов "{self.object.name}" успешно обновлена!'
|
f'Группа вариантов "{self.object.name}" успешно обновлена!'
|
||||||
@@ -184,14 +182,6 @@ class ProductVariantGroupUpdateView(LoginRequiredMixin, UpdateView):
|
|||||||
messages.error(self.request, f'Ошибка при сохранении: {str(e)}')
|
messages.error(self.request, f'Ошибка при сохранении: {str(e)}')
|
||||||
return self.form_invalid(form)
|
return self.form_invalid(form)
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _recalculate_priorities(variant_group):
|
|
||||||
"""Пересчитывает приоритеты товаров в группе"""
|
|
||||||
items = variant_group.items.all().order_by('id')
|
|
||||||
for idx, item in enumerate(items, start=1):
|
|
||||||
item.priority = idx
|
|
||||||
item.save(update_fields=['priority'])
|
|
||||||
|
|
||||||
|
|
||||||
class ProductVariantGroupDeleteView(LoginRequiredMixin, DeleteView):
|
class ProductVariantGroupDeleteView(LoginRequiredMixin, DeleteView):
|
||||||
"""Удаление группы вариантов с подтверждением"""
|
"""Удаление группы вариантов с подтверждением"""
|
||||||
|
|||||||
Reference in New Issue
Block a user