如何在Django中使用其他参数时绑定表格

问题描述 投票:0回答:1

我尝试用表单提交POST请求后执行.is_valid()

form = DrinkForm(request.POST)

类似,“问题”是此表单具有其他参数。

forms.py:

class DrinkForm(forms.Form):
    def __init__(self, language, account_id, configurations, *args, **kwargs):
        super(DrinkForm, self).__init__(*args, **kwargs)
        translation.activate(language)

使用此方法,我不知道如何绑定表格(也找不到有关此案例的任何指南或示例)。

当我打印带有常规参数的视图时,一切正常,但是如果添加request.POST,我什么也没得到。

form_ok = DrinkForm('english', request.session['account_id'], configurations)  # OK
form_not_ok = DrinkForm(request.POST)  # Needs parameters
form_how_to = DrinkForm('english', request.session['account_id'], configurations, request.POST)  # How to?

编辑:已添加表单和视图代码

def create_drink(request):
    if request.method == 'POST':
        c = {}
        c.update(csrf(request))
        data = DrinkForm.build_create_data(request.POST)
        try:  # Tries to create the new drink
            account = Account.objects.get(id=request.session['account_id'])
            drinks_conf = DrinksConf.objects.get(account_id=request.session['account_id'])
            form = DrinkForm(get_language(request), request.session['account_id'], drinks_conf, request.POST)
            print(form)  # Nothing is printed!
            if form.is_valid():
                print('valid?')  # Not printed!
                with transaction.atomic():
                    stock = DrinkStock.objects.create(account=account, stock=0)
                    Drink.objects.create(account=account, name=data['name'], cost=data['cost'], stock=stock,
                                         stock_by=data['stock_by'])
                return JsonResponse(DRINK_CREATE_SUCCESS)
            else:
                print('oh no not valid')  # Neither printed!! What the..?
                return JsonResponse(form_error_response(form.errors))
        except:  # Unknown exception
            return JsonResponse(UNKNOWN_EXCEPTION)

forms.py:

class DrinkForm(forms.Form):
    def __init__(self, language, account_id, drinks_conf, *args, **kwargs):
        super(DrinkForm, self).__init__(*args, **kwargs)
        translation.activate(language)
        self.account_id = account_id  # will be used in the future
        self.drinks_conf = drinks_conf
        options = (
            (1, translation.gettext('Units')),
            (3, translation.gettext('Litters'))
        )
        self.fields['name'] = forms.CharField(
            max_length=100,
            required=True,
            label=translation.gettext('Name'),
            widget=forms.TextInput(attrs={'class': 'form-control dynamic_object_submit'})
        )
        self.fields['cost'] = forms.DecimalField(
            max_digits=14,
            decimal_places=2,
            required=True,
            label=translation.gettext('Cost'),
            widget=forms.NumberInput(attrs={'class': 'form-control dynamic_object_submit'})
        )
        self.fields['stock_by'] = forms.ChoiceField(
            required=True,
            label=translation.gettext('Stock/cost by'),
            choices=options,
            widget=forms.Select(attrs={'class': 'form-control dynamic_object_submit'})
        )

    def clean_cost(self):
        if self.drinks_conf.cost_control is True:
            data = self.cleaned_data['cost']
            if data < 0:
                raise forms.ValidationError(translation.gettext("Cost can't be negative"))

    @staticmethod
    def build_create_data(querydict):
        return {
            'name': querydict.get('name', None),
            'cost': querydict.get('cost', None),
            'stock_by': querydict.get('stock_by', None),
        }

我正在尝试对表单提交POST请求后执行.is_valid()。 form = DrinkForm(request.POST)像这样,“问题”是此表单具有其他参数。 form.py:类DrinkForm(forms ....

python django forms view model
1个回答
0
投票

您可以在字段标签上使用gettext_lazy在请求时提供翻译。现在,您无需将语言传递到初始化方法中,并且发布数据应该正确绑定,因为您没有动态添加字段

© www.soinside.com 2019 - 2024. All rights reserved.