Django:在ClassBased视图中将min和max属性传递给datepicker

时间:2018-09-11 17:08:33

标签: django-views

我正在创建一个多用户费用提交系统。出于这个问题的目的,有两个模型:ClaimJourney。用户创建一个索赔,每个索赔可以有多个旅程。

在旅程CreateView中,以下代码:

  • 根据在网址中传递的索赔pk,自动填充正在记录旅程的索赔下拉列表。
  • 基于已登录的用户,仅显示该用户的声明(在下拉列表中)
  • 设置<input>的HTML属性; type=date呈现日期选择器,而min='2018-09-10'指定不允许的日期范围:

date with allowable range

在以下视图中,我正在计算最小日期和最大日期,这些日期会在健全性检查中正确输出:

class JourneyCreateView(CreateView):
    model = Journey
    form_class = JourneyForm

    def get_initial(self):
        try:
            # Calculate date limit for the date picker
            min = Claim.objects.get(id=self.kwargs['claim']).week_commencing
            max = min + timedelta(days=7)

            # Obtain the claim ID from the URL
            claim = self.kwargs['claim']

            # Sanity check
            print (claim, min, max)

            return {'claim': claim, 'min':min, 'max':max}

        except Exception as ex:
            print (ex)
            return {}

    def get_form_kwargs(self, *args, **kwargs):
        # Only show claims owned by the logged in user in the claim dropdown
        kwargs = super().get_form_kwargs(*args, **kwargs)
        kwargs['alloweduser'] = self.request.user.id
        return kwargs

和表格:

class JourneyForm(forms.ModelForm):
    # set html attribs which will apply to the form.
    date = forms.CharField(widget=forms.TextInput(attrs={'type':'date',
                                                        'min':'2018-09-10'
                                                        }))
    class Meta:
        model = Journey
        fields = ['date', 'distance','claim']

    def __init__(self,alloweduser,*args,**kwargs):
        # Make sure only to display the user's own claims.
        super (JourneyForm,self ).__init__(*args,**kwargs) 
        self.fields['claim'].queryset = Claim.objects.filter(tech_id=alloweduser)

在此代码中,claim还返回get_initial(),并正确地使用当前声明预先填充了声明下拉列表:

return {'claim': claim, 'min':min, 'max':max}

但是,令我感到困惑的是,我如何访问min在表单的第三行中返回的maxget_initial()变量,替换手动测试字符串。

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。我的解决方案是:

CreateView中,将逻辑放在get_from_kwargs中,而不是get_initial上:

d = Claim.objects.get(id=self.kwargs['claim']).week_commencing
kwargs['min'], kwargs['max'] = d, d+timedelta(days=7)

在覆盖min中的max时,__init__ModelForm成为参数:

def __init__(self,alloweduser,min,max,*args,**kwargs):
    # Make sure only to display the user's own claims.
    super (JourneyForm,self ).__init__(*args,**kwargs) 
    self.fields['claim'].queryset = Claim.objects.filter(tech_id=alloweduser)
    self.fields['date'] = forms.CharField(widget=forms.TextInput(attrs={'type':'date',
                                                    'min':min, 'max':max
                                                    }))