将表单参数传递给Model Formset

时间:2014-09-17 05:51:09

标签: django forms django-forms

我创建了:

  1. 模特
  2. 相应的模型表格
  3. 使用2中的表单创建模型formset的对应视图。
  4. 以下是代码:

    1.Model:

    class Expenditure(models.Model):
        exp_owner= models.CharField(default='None',max_length=50)
        exp_date = models.DateTimeField("Expenditure_Date")
        description = models.CharField(max_length=1000)
        amount = models.FloatField(default=0)
        currency = models.CharField(max_length=15,default="MYR",editable=True)
        exp_pocket = models.ForeignKey(Pockets, null=True, blank=True)
        exp_type = models.ForeignKey(Types_of_Expenditures)
        class Meta:
            unique_together = ('exp_date', 'description',)
        def __unicode__(self):
            return self.description
    

    2.对应的模型形式:

    class ExpenditureForm(forms.ModelForm):
        #def __init__(self,*args, **kwargs):
            #self.requestUser = kwargs.pop("RequestUser")
            #super(ExpenditureForm, self).__init__(*args, **kwargs)
            #print "User who requested this form is ",self.requestUser
    
        def initialExpType(self):
            lengthOfTypesOfExpenditures=len(Types_of_Expenditures.objects.filter(Expenditure_owner=self.requestUser))
            print "current types of expenditures are ",lengthOfTypesOfExpenditures
            if lengthOfTypesOfExpenditures > 0:
                return Types_of_Expenditures.objects.filter(Expenditure_owner=self.requestUser)[:1].get()
            else:
                return "Null"
        exp_date = forms.DateTimeField(widget=AdminDateWidget(attrs={'class':'datetimeField'}))
        description = forms.CharField(show_hidden_initial=True,max_length=1000)
        exp_type = forms.ModelChoiceField(queryset=Types_of_Expenditures.objects.filter(Expenditure_Type_Enable=True),initial=initialExpType)
        amount = forms.FloatField(initial=0)
    exp_pocket = forms.ModelChoiceField(show_hidden_initial=True,queryset=Pockets.objects.all(),initial=Pockets.objects.filter()[:1].get())
        class Meta:
            model = Expenditure
    

    3.对应观点

    我将相应的表格称为视图中的第2点:

    ExpFormSet = modelformset_factory(Expenditure,extra=10,max_num=10,
                    fields=('exp_date', 'description','exp_type','amount','exp_pocket'),
                    can_delete=False,form=ExpenditureForm))
    

    并且效果很好。

    问题 我想将登录用户传递给我的表单,即我想将来自views.py的request.user传递给表单,并通过添加 init 方法完成表单中的更改(目前在上面的代码中评论过),但我不知道如何将登录用户从views.py传递给此表单。

    我试过了什么? 此question

    中提到的解决方案

    然而,这种剂量似乎适用于模型来源。

    1. 尝试在formset中调用下面的代码,我知道它错了但只是试用了!

      ExpFormSet = modelformset_factory(Expenditure,extra=10,max_num=10,
                  fields=('exp_date', 'description','exp_type','amount','exp_pocket'),
                  can_delete=False,form=ExpenditureForm(RequestUser=str(request.user)))
      
    2. 这样做我确实从表格的 init 输出了print语句 请求此表单的用户是admin

      然而,我得到了RequestUser' 异常类型:KeyError 例外值:

      任何建议?

1 个答案:

答案 0 :(得分:-1)

ModelForm中,您只需使用

传递请求即可
ExpFormSet = modelformset_factory(Expenditure,extra=10,max_num=10,
            fields=('exp_date', 'description','exp_type','amount','exp_pocket'),
            can_delete=False,form=ExpenditureForm(request=request))

您可以使用ExpenditureForm中的请求以

的形式登录表单中的用户
class ExpenditureForm(forms.ModelForm):
    def __init__(self,*args, **kwargs):
        print "User who requested this form is ",kwargs['request'].user
        super(ExpenditureForm, self).__init__(*args, **kwargs)