我正在创建一个多用户费用提交系统。出于这个问题的目的,有两个模型:Claim
和Journey
。用户创建一个索赔,每个索赔可以有多个旅程。
在旅程CreateView
中,以下代码:
<input>
的HTML属性; type=date
呈现日期选择器,而min='2018-09-10'
指定不允许的日期范围:在以下视图中,我正在计算最小日期和最大日期,这些日期会在健全性检查中正确输出:
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
在表单的第三行中返回的max
和get_initial()
变量,替换手动测试字符串。
答案 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
}))