首页 > 解决方案 > Django:在 ClassBased 视图中将 min 和 max 属性传递给 datepicker

问题描述

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

在 JourneyCreateView中,以下代码:

允许范围内的日期

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

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}

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

标签: django-views

解决方案


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

在 中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)

然后在覆盖minmax成为参数:__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
                                                    }))

推荐阅读