django-views - Django:在 ClassBased 视图中将 min 和 max 属性传递给 datepicker
问题描述
我正在创建一个多用户的费用提交系统。出于这个问题的目的,有两个模型:Claim
和Journey
。用户创建一个索赔,每个索赔可以有多个旅程。
在 JourneyCreateView
中,以下代码:
- 根据在 URL 中传递的声明 pk,自动填充正在记录旅程的声明下拉列表。
- 根据登录的用户,仅显示该用户的声明(在下拉列表中)
<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
andmax
变量来替换手动测试字符串。get_initial()
解决方案
我自己解决了这个问题。我的解决方案是:
在 中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
}))
推荐阅读
- c# - Visual Studio 2013 中本地数据库连接错误
- python - XOR NN 无法通过 2 个隐藏节点和 sigmoid 激活来学习?
- linux - 为什么添加“-Wl,-static -lmy_static_lib”会破坏库搜索路径?
- python - (Python(分析))无法解析“熊猫”。此模块可能缺少 IntelliSense
- c# - 如何使用 lambda 表达式在子集合中使用 where 条件?
- c# - C#如何订阅使用委托的事件?
- c++ - 处理OKCallback崩溃
- javascript - 如何使用 javascript 使用多个组合框设置多个事件(更改时)
- python - Python Sockets 通过 HTTP 下载 jpg
- ubuntu - 安装tomcat后无法启动Ubuntu 16.04