Мой набор форм не действителен, и я не могу получить очищенные_данные каждой формы.
У меня есть 3 модели ниже,
class MenuItem(TranslatableModel):
item_id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
categories = models.ManyToManyField(MenuCategory, related_name='menu_items')
translations = TranslatedFields(
name=models.CharField(_('name'), max_length=200),
slug=models.SlugField(blank=True, null=True, unique=True),
description=models.TextField(_('description'), blank=True, null=True)
)
price = models.DecimalField(_('price'), max_digits=10, decimal_places=2, default=0)
image = models.ImageField(_('image'), upload_to='menu_items/%Y/%m/%d', blank=True, null=True)
is_available = models.BooleanField(_('is available'), default=True)
created = models.DateTimeField(_('created'), auto_now_add=True)
updated = models.DateTimeField(_('updated'), auto_now=True)
def __str__(self):
return f'{self.name}'.title()
def get_absolute_url(self):
return reverse('menu_management:item_detail', args=[self.item_id, self.slug])
class MenuOptionGroup(TranslatableModel):
group_id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='options_groups')
translations = TranslatedFields(
name=models.CharField(_('name'), max_length=200),
slug=models.SlugField(blank=True, null=True, unique=True)
)
is_required = models.BooleanField(_('is required'), default=False)
max_choices = models.IntegerField(_('max choices'), blank=True, null=True)
created = models.DateTimeField(_('created'), auto_now_add=True)
updated = models.DateTimeField(_('updated'), auto_now=True)
def __str__(self):
return f'{self.name}'.title()
class MenuOption(TranslatableModel):
option_id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
group = models.ForeignKey(MenuOptionGroup, on_delete=models.CASCADE, related_name='options')
translations = TranslatedFields(
name=models.CharField(_('name'), max_length=200),
slug=models.SlugField(blank=True, null=True, unique=True)
)
image = models.ImageField(_('image'), upload_to='menu_options/%Y/%m/%d', blank=True, null=True)
price_change = models.DecimalField(_('price change'), max_digits=10, decimal_places=2, default=0)
created = models.DateTimeField(_('created'), auto_now_add=True)
updated = models.DateTimeField(_('updated'), auto_now=True)
def __str__(self):
return f'{self.name}'.title()
Из этих 3 классов я пытаюсь создать набор форм, который будет проходить через MenuOptionGroup
и подбирать соответствующие им menu_option
. Моя форма выглядит так, как показано ниже.
class MenuOptionGroupForm(TranslatableModelForm):
menu_option = forms.ModelChoiceField(queryset=MenuOption.objects.none(),
empty_label="No options",
required=False)
class Meta:
model = MenuOptionGroup
# Include the fields that should be editable in the form
exclude = ['group_id']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance and hasattr(self.instance, 'options'):
self.fields['menu_option'].queryset = self.instance.options.all()
def clean_menu_option(self):
# The cleaned_data dictionary may not exist if the form hasn't been validated
menu_option = self.cleaned_data.get('menu_option', None)
return menu_option
Но я получаю эту ошибку формы.
[{'menu_option': ['Select a valid choice. That choice is not one of the available choices.'], 'name': ['This field is required.'], 'group_id': ['This field is required.']}, {'menu_option': ['Select a valid choice. That choice is not one of the available choices.'], 'name': ['This field is required.'], 'group_id': ['This field is required.']}]
Ниже вы можете видеть, что набор форм хорошо извлекает все MenuOptionGroup
и соответствующие им MenuOption
, но когда я пытаюсь добавить в корзину, то вижу вышеуказанную ошибку.
frontend_add_to_cart
Ниже (на всякий случай) приведена моя функция просмотра.
@require_POST
def cart_add(request, item_id):
cart = Cart(request)
menu_item = get_object_or_404(MenuItem, item_id=item_id)
form = CartAddItemForm(request.POST)
# Create a formset for the MenuOptionGroup associated with the menu_item
formset = None
options = []
if 'options_groups-TOTAL_FORMS' in request.POST.keys():
MenuOptionGroupFormSet = inlineformset_factory(MenuItem, MenuOptionGroup, form=MenuOptionGroupForm, extra=1)
formset = MenuOptionGroupFormSet(request.POST, instance=menu_item)
if form.is_valid():
cd = form.cleaned_data
if formset:
if formset.is_valid():
for form in formset:
options.append(form.cleaned_data.get('menu_option'))
else:
print(formset.errors)
print("VOILA")
print(options)
cart.add(menu_item=menu_item,
quantity=cd['quantity'],
override_quantity=cd['override']`your text`,
options=options)
return redirect('cart:cart_detail')