@Vitalii181190
Начинающий вэб-разработчик

Почему поле ModelChoiceField при formset_factory не работает?

forms.py
class AddCurrencyForm(forms.Form):

    def __init__(self, servers, *args, **kwargs):
        super(AddCurrencyForm, self).__init__(*args, **kwargs)
        self.fields['server'].queryset = servers
       
    server = forms.ModelChoiceField(queryset=Servers.objects.all(), empty_label=None, required=False)
    price = forms.DecimalField(required=False, decimal_places=None, min_value=0, max_value=10000000.00,
                               widget=forms.TextInput(attrs={}))
    availability = forms.IntegerField(required=False, min_value=0, max_value=10000000,
                                      widget=forms.TextInput(attrs={}))

utils.py
class ContextAddAvailability(LoginRequiredMixin, ContextList, DetailView):

    def post(self, request, **kwargs):

        servers = Servers.objects.filter(id_num=self.kwargs.get('sale'))
        AddCurrencyFormSet = formset_factory(AddCurrencyForm,
                                             extra=len(Servers.objects.filter(id_num=self.kwargs.get('sale'))))
        if request.method == 'POST':

            formset = AddCurrencyFormSet(request.POST, servers)
            if formset.is_valid():
                owner = Customer.objects.get(user=request.user)
                for form in formset:
                    server = form.cleaned_data['server']
                    if 'price' in form.cleaned_data:
                        price = form.cleaned_data['price']
                    else:
                        price = Currency.objects.get(owner=owner).price
                    if 'availability' in form.cleaned_data:
                        availability = form.cleaned_data['availability']
                    else:
                        availability = Currency.objects.get(owner=owner).availability

                    if Currency.objects.filter(owner=owner, server=server).exists():
                        user = Currency.objects.get(owner=owner, server=servers)
                        user.price = price
                        user.availability = availability
                        user.date = timezone.now()
                        user.save()
                    else:
                        Currency.objects.create(
                            owner=owner,
                            games=Games.objects.get(pk=self.kwargs.get('sale')),
                            server=server,
                            price=price,
                            availability=availability,
                            date=timezone.now()
                        )
                context = {
                    'AddCurrency': formset,
                    'form_search': SearchForm(),
                    'games': Games.objects.get(pk=self.kwargs.get('sale')),
                    'user_name': Customer.objects.get(user=self.request.user),
                    'form_valid': _('Информация сохранена')
                }

                return render(request, 'Pay/sale/sell_availability_detail.html', context)

            else:
                context = {
                    'AddCurrency': formset,
                    'form_search': SearchForm(),
                    'games': Games.objects.get(pk=self.kwargs.get('sale')),
                    'user_name': Customer.objects.get(user=self.request.user)
                }
            return render(request, 'Pay/sale/sell_availability_detail.html', context)

ошибка:
File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\forms\forms.py", line 440, in _clean_fields
    value = bf.initial if field.disabled else bf.data
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\forms\boundfield.py", line 127, in data
    return self.form._widget_data_value(self.field.widget, self.html_name)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\forms\forms.py", line 224, in _widget_data_value
    return widget.value_from_datadict(self.data, self.files, html_name)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\forms\widgets.py", line 292, in value_from_datadict
    return data.get(name)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\query.py", line 482, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Vitaliy\PycharmProjects\Funpay\venv\lib\site-packages\django\db\models\sql\query.py", line 1374, in build_filter
    arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
HTTP GET /ru/currency/1/trade 500 [0.67, 127.0.0.1:52194]
  • Вопрос задан
  • 53 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы