Django formset-基于用户cookie验证输入?

Django formset-基于用户cookie验证输入?,django,forms,validation,django-forms,formsets,Django,Forms,Validation,Django Forms,Formsets,我有一个Django表单(TestForm),它包含一个字段quantity。我还有一个Django表单集(TestFormset),它包含我的TestForm的多个实例 我想为TestFormset编写一个自定义clean()方法,该方法验证在多个TestForms中指定的数量之和是否等于存储在会话变量中的一个数字max_quantity 我知道我能够在views.py中执行此验证(例如,在我的表单集被验证和清理之后,我可以手动汇总TestForms中的“数量”变量,并检查以确保它们与requ

我有一个Django表单(TestForm),它包含一个字段quantity。我还有一个Django表单集(TestFormset),它包含我的TestForm的多个实例

我想为TestFormset编写一个自定义clean()方法,该方法验证在多个TestForms中指定的数量之和是否等于存储在会话变量中的一个数字max_quantity

我知道我能够在views.py中执行此验证(例如,在我的表单集被验证和清理之后,我可以手动汇总TestForms中的“数量”变量,并检查以确保它们与request.session['max_quantity']相等,如果发现任何问题,就会抛出错误)

但理想情况下,我希望将所有表单验证逻辑移到forms.py的clean()方法中。但是,我不知道如何将外部值传递到未链接到其单个表单的表单集中

这可能吗

forms.py

from django.forms import BaseFormSet

class TestForm(forms.Form):
    quantity = forms.IntegerField()

class BaseTestFormset(BaseFormset):
    def clean(self):
        if any(self.errors):

            # Don't bother validating the formset unless each form is valid on its own

            return

        quantity = 0

        for form in self.forms:
            quantity += form.cleaned_data['quantity']

        # IF QUANTITY IS NOT EQUAL TO MAX_QUANTITY, THROW AN ERROR...
        # ...BUT HOW DO WE GET THE MAX_QUANTITY INTO THIS FUNCTION?
from .forms import TestForm, BaseTestFormset

def serve_form(request):

    TestFormSet = formset_factory(TestForm, formset=BaseTestFormset)

    if request.method == 'POST':
        formset = TestFormSet(request.POST)

        # This method should check to ensure that the sum of quantities within our formsets does not exceed max_quantity
        if formset.is_valid():
              # Proceed to take action
    else:
        # Sample initial data
        formset = TestFormSet(initial=[{'quantity': 5}, {'quantity': 7}])

    # I CAN PASS MAX_QUANTITY INTO THE TEMPLATE... BUT HOW DO I GET IT INTO THE FORMSET VALIDATION METHOD?
    return render(request, 'template.html', {'formset': formset, 'max_quantity': request.session['max_quantity']}
视图.py

from django.forms import BaseFormSet

class TestForm(forms.Form):
    quantity = forms.IntegerField()

class BaseTestFormset(BaseFormset):
    def clean(self):
        if any(self.errors):

            # Don't bother validating the formset unless each form is valid on its own

            return

        quantity = 0

        for form in self.forms:
            quantity += form.cleaned_data['quantity']

        # IF QUANTITY IS NOT EQUAL TO MAX_QUANTITY, THROW AN ERROR...
        # ...BUT HOW DO WE GET THE MAX_QUANTITY INTO THIS FUNCTION?
from .forms import TestForm, BaseTestFormset

def serve_form(request):

    TestFormSet = formset_factory(TestForm, formset=BaseTestFormset)

    if request.method == 'POST':
        formset = TestFormSet(request.POST)

        # This method should check to ensure that the sum of quantities within our formsets does not exceed max_quantity
        if formset.is_valid():
              # Proceed to take action
    else:
        # Sample initial data
        formset = TestFormSet(initial=[{'quantity': 5}, {'quantity': 7}])

    # I CAN PASS MAX_QUANTITY INTO THE TEMPLATE... BUT HOW DO I GET IT INTO THE FORMSET VALIDATION METHOD?
    return render(request, 'template.html', {'formset': formset, 'max_quantity': request.session['max_quantity']}

与表单一样,如果您希望在方法中访问某些内容,则需要将其传递到某个地方。如果愿意,可以在初始化器中执行此操作:

class BaseTestFormset(forms.BaseFormSet):
    def __init__(self, *args, **kwargs):
        self.max_quantity = kwargs.pop('max_quantity', None)
        super(BaseTestFormset, self).__init__(*args, **kwargs)

    def clean(self):
        ...
        if quantity > self.max_quantity:
            ...
并且认为:

if request.method == 'POST':
    formset = TestFormSet(request.POST, max_quantity=request.session['max_quantity'])

当然这很有道理。万分感谢:)