Django:inlineformset_factory,传递参数/变量

时间:2016-02-20 11:41:27

标签: python django django-forms

我对django很新,我遇到了问题,想请求帮助。

我将自定义参数传递给表单

时出错
KeyError at /someurl
'my_arg'

    Request Method: GET
    Request URL:    http://localhost:8000/
    Django Version: 1.8.2
    Exception Type: KeyError
    Exception Value: 'my_arg'
    Exception Location: ..../forms.py in __init__, line 108(points at 'my_arg = kwargs.pop('my_arg')' line)
    Python Executable:  C:\Python27\python.exe
    Python Version: 2.7.10
    Python Path:    
    ['C:\\Users\\lolwat\\Desktop\\ITSWEBSITE',
     'C:\\Windows\\system32\\python27.zip',
     'C:\\Python27\\DLLs',
     'C:\\Python27\\lib',
     'C:\\Python27\\lib\\plat-win',
     'C:\\Python27\\lib\\lib-tk',
     'C:\\Python27',
     'C:\\Python27\\lib\\site-packages']

它也在错误页面上说明了这一点:

Error during template rendering
    ...
    {% for field in form %}
    ...

这是我的表格:

class BaseFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
    self.my_arg = kwargs.pop("my_arg")
    super(BaseFormSet, self).__init__(*args, **kwargs)

class SomeForm(ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        my_arg = kwargs.pop('my_arg')
        super(SomeForm, self).__init__(*args, **kwargs)

我的意见:

myformset = inlineformset_factory(modelA, modelB, formset = BaseFormSet, form=SomeForm, extra=1, can_delete=True)

def someview(request, obj_id):
    var1 = get_object_or_404(SomeModel, id = obj_id)
    somevalue = var1.ModelFieldValue
    form = myformset (request.POST, my_arg=somevalue)
    if request.method == 'POST':
        ...
    else:
        form = myformset(instance = myinstance, my_arg=somevalue)

     return render(....)

我做错了什么或我做得对吗?非常感谢。

更新

我尝试使用myformset.form = staticmethod(curry(SomeForm, my_arg=somevalue))

我的观点如下:

from django.utils.functional import curry

myformset = inlineformset_factory(modelA, modelB, formset = BaseFormSet, form=SomeForm, extra=1, can_delete=True)

def someview(request, obj_id):
    var1 = get_object_or_404(SomeModel, id = obj_id)
    somevalue = var1.ModelFieldValue
    myformset.form = staticmethod(curry(SomeForm, my_arg=somevalue))
    form = myformset (request.POST, my_arg=somevalue)
    if request.method == 'POST':
        ...
    else:
        form = myformset(instance = myinstance, my_arg=somevalue)

     return render(....)

它正在运行,我正在使用my_arg通过ModelChoiceField过滤SomeForm的__init__查询集,我的表单如下所示:

class SomeForm(ModelForm):
   MyField = ModelChoiceField(queryset=SomeModel.objects.none())
    def __init__(self, *args, **kwargs):
        my_arg = kwargs.pop('my_arg', None)
        super(SomeForm, self).__init__(*args, **kwargs)
        self.fields['MyField'].queryset = SomeModel.objects.filter(fkey = my_arg)

保存后我收到<DjangoObject> is not JSON serializable错误

1 个答案:

答案 0 :(得分:1)

您收到此错误是因为您的内部表单SomeForm未在my_arg中收到kwargs作为参数。并且因为您使用kwargs.pop('my_arg')而没有默认值 - &gt;你得到KeyError。如果您使用提供的默认值.popkwargs.pop('my_arg', None)),则不会获得KeyError

如果您确实需要将my_arg传递到内部SomeForm,请查看以下问题:hereherehere

更新:

据我所知,您需要my_arg来过滤字段的查询集。好吧,你不需要inner_form.__init__,但是在formset.__init__方法中构建所有表单之后。

这样的事情:

class BaseFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        my_arg = kwargs.pop("my_arg")
        super(BaseFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.fields['my_field'].queryset = SomeModel.objects.filter(fkey = my_arg)