django ModelForm DateField 初始值不起作用
django ModelForm DateField initial value not working
我想在我的 ModelForm 中为日期字段设置初始数据,但它不起作用。下面是我的代码。
def get_date():
return timezone.localtime(timezone.now()).date()
模型形式:
class TransferPacketForm(forms.ModelForm):
party = forms.ModelChoiceField(
required=True, queryset=Party.objects.all(),
widget=forms.Select(
attrs={
'class': 'form-control'
}
)
)
transferred_on = forms.DateField(
required=True, initial=get_date, input_formats=['%d-%m-%Y'],
validators=[validators.get('min_value')(date(2000, 01, 01))],
widget=forms.DateInput(
format='%d-%m-%Y',
attrs={
'autofocus': 'true', 'class': 'form-control'
}
)
)
transferred_roi = forms.DecimalField(
required=True, max_digits=3, decimal_places=2,
min_value=1.00, max_value=5.00,
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
transferred_amount = forms.IntegerField(
required=True, min_value=1, widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
class Meta:
model = Packet
fields = (
'transferred_on', 'transferred_amount',
'transferred_remark', 'transferred_roi',
'party'
)
widgets = {
'transferred_remark': forms.Textarea(
attrs={
'class': 'form-control'
}
)
}
查看:
class TransferPacketView(LoginRequiredMixin, UpdateView):
model = Packet
form_class = TransferPacketForm
http_method_names = ['get', 'post']
template_name = 'update_templates/transfer_packet.html'
def get_success_url(self):
return reverse(
'girvi:transferred_packet',
kwargs={
'pk': self.get_object()
}
)
def get(self, request, *args, **kwargs):
return super(TransferPacketView, self).get(request, *args, **kwargs)
def form_valid(self, form):
pkt_obj = self.get_object()
pkt_obj.is_transferred = True
pkt_obj.save()
return redirect(
self.get_success_url()
)
表格:
<tr><th><label for="id_transferred_on">Transferred on:</label></th><td><input autofocus="true" class="form-control" id="id_transferred_on" name="transferred_on" type="text" value="15-02-2015" /></td></tr>
<tr><th><label for="id_transferred_amount">Transferred amount:</label></th><td><input class="form-control" id="id_transferred_amount" name="transferred_amount" type="text" /></td></tr>
<tr><th><label for="id_transferred_remark">Transferred remark:</label></th><td><textarea class="form-control" cols="40" id="id_transferred_remark" maxlength="150" name="transferred_remark" rows="10">
</textarea></td></tr>
<tr><th><label for="id_transferred_roi">Transferred roi:</label></th><td><input class="form-control" id="id_transferred_roi" name="transferred_roi" type="text" /></td></tr>
<tr><th><label for="id_party">Party:</label></th><td><select class="form-control" id="id_party" name="party">
<option value="" selected="selected">---------</option>
<option value="2">ram pal</option>
<option value="1">shyam pal</option>
</select></td></tr>
但是 html 表单在没有任何初始数据的情况下呈现。
Html 表单域:
<div class="form-group form-group-sm clearfix">
<label class="control-label col-xs-2 col-xs-offset-6" for="id_transferred_on">Dated</label>
<div class="col-xs-4 pull-right">
<div id="datepicker" class="input-group date">
<input id="id_transferred_on" class="form-control" type="text" name="transferred_on" autofocus="true">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
谁能告诉我哪里出了问题???为什么未将值设置为初始数据。
模板:
<form id="transferPacketForm" class="form form-horizontal width-500 center-block theme-font" role="form" action="." method="post">{% csrf_token %}
<!-- DIV -->
{% if form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{% for field in form %}
{% if field.errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>{{ field.label }}: {{ field.errors|striptags }}</span><br>
{% endif %}
{% endfor %}
{% for error in form.non_field_errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>Error: {{ error|striptags }}</span>
{% endfor %}
</div>
{% endif %}
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm clearfix">
<label for="id_{{ form.transferred_on.name }}" class="control-label col-xs-2 col-xs-offset-6">Dated</label>
<div class="col-xs-4 pull-right">
<div class="input-group date" id='datepicker'>
{{ form.transferred_on }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.party.name }}" class="control-label col-xs-4">{{ form.party.label }}</label>
<div class="col-xs-8">
{{ form.party }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_amount.name }}" class="control-label col-xs-4">Amount</label>
<div class="col-xs-8">
{{ form.transferred_amount }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_roi.name }}" class="control-label col-xs-4">Interest</label>
<div class="col-xs-8">
{{ form.transferred_roi }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_remark.name }}" class="control-label col-xs-4">Remark</label>
<div class="col-xs-8">
{{ form.transferred_remark }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="btn-toolbar" align="middle">
<button type="submit" class="btn btn-primary btn-color btn-bg-color">Submit</button>
<button type="button" class="btn btn-danger btn-color btn-bg-color" onclick="window.close()">Close</button>
</div>
<!-- /DIV -->
</form>
如果您没有将模型实例传递给表单,它只会呈现初始值。试试这个:
p = Packet.objects.filter(transferred_on__isnull=True)[0]
# or simply
p = Packet()
f = TransferPacketForm(instance=p)
print(f['transferred_on'])
该字段没有初始值,但如果您这样做:
f = TransferPacketForm()
print(f['transferred_on'])
会的。看看吧。
编辑
当您将 initial
字典传递给表单时它不适用,它实际上会检查模型的字段是否为空并使用字典中的值。因此,您的解决方法不是使用字段的 initial
,而是使用表单的 initial
,即通过视图的 get_initial()
。
我想在我的 ModelForm 中为日期字段设置初始数据,但它不起作用。下面是我的代码。
def get_date():
return timezone.localtime(timezone.now()).date()
模型形式:
class TransferPacketForm(forms.ModelForm):
party = forms.ModelChoiceField(
required=True, queryset=Party.objects.all(),
widget=forms.Select(
attrs={
'class': 'form-control'
}
)
)
transferred_on = forms.DateField(
required=True, initial=get_date, input_formats=['%d-%m-%Y'],
validators=[validators.get('min_value')(date(2000, 01, 01))],
widget=forms.DateInput(
format='%d-%m-%Y',
attrs={
'autofocus': 'true', 'class': 'form-control'
}
)
)
transferred_roi = forms.DecimalField(
required=True, max_digits=3, decimal_places=2,
min_value=1.00, max_value=5.00,
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
transferred_amount = forms.IntegerField(
required=True, min_value=1, widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
class Meta:
model = Packet
fields = (
'transferred_on', 'transferred_amount',
'transferred_remark', 'transferred_roi',
'party'
)
widgets = {
'transferred_remark': forms.Textarea(
attrs={
'class': 'form-control'
}
)
}
查看:
class TransferPacketView(LoginRequiredMixin, UpdateView):
model = Packet
form_class = TransferPacketForm
http_method_names = ['get', 'post']
template_name = 'update_templates/transfer_packet.html'
def get_success_url(self):
return reverse(
'girvi:transferred_packet',
kwargs={
'pk': self.get_object()
}
)
def get(self, request, *args, **kwargs):
return super(TransferPacketView, self).get(request, *args, **kwargs)
def form_valid(self, form):
pkt_obj = self.get_object()
pkt_obj.is_transferred = True
pkt_obj.save()
return redirect(
self.get_success_url()
)
表格:
<tr><th><label for="id_transferred_on">Transferred on:</label></th><td><input autofocus="true" class="form-control" id="id_transferred_on" name="transferred_on" type="text" value="15-02-2015" /></td></tr>
<tr><th><label for="id_transferred_amount">Transferred amount:</label></th><td><input class="form-control" id="id_transferred_amount" name="transferred_amount" type="text" /></td></tr>
<tr><th><label for="id_transferred_remark">Transferred remark:</label></th><td><textarea class="form-control" cols="40" id="id_transferred_remark" maxlength="150" name="transferred_remark" rows="10">
</textarea></td></tr>
<tr><th><label for="id_transferred_roi">Transferred roi:</label></th><td><input class="form-control" id="id_transferred_roi" name="transferred_roi" type="text" /></td></tr>
<tr><th><label for="id_party">Party:</label></th><td><select class="form-control" id="id_party" name="party">
<option value="" selected="selected">---------</option>
<option value="2">ram pal</option>
<option value="1">shyam pal</option>
</select></td></tr>
但是 html 表单在没有任何初始数据的情况下呈现。
Html 表单域:
<div class="form-group form-group-sm clearfix">
<label class="control-label col-xs-2 col-xs-offset-6" for="id_transferred_on">Dated</label>
<div class="col-xs-4 pull-right">
<div id="datepicker" class="input-group date">
<input id="id_transferred_on" class="form-control" type="text" name="transferred_on" autofocus="true">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
谁能告诉我哪里出了问题???为什么未将值设置为初始数据。
模板:
<form id="transferPacketForm" class="form form-horizontal width-500 center-block theme-font" role="form" action="." method="post">{% csrf_token %}
<!-- DIV -->
{% if form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{% for field in form %}
{% if field.errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>{{ field.label }}: {{ field.errors|striptags }}</span><br>
{% endif %}
{% endfor %}
{% for error in form.non_field_errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>Error: {{ error|striptags }}</span>
{% endfor %}
</div>
{% endif %}
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm clearfix">
<label for="id_{{ form.transferred_on.name }}" class="control-label col-xs-2 col-xs-offset-6">Dated</label>
<div class="col-xs-4 pull-right">
<div class="input-group date" id='datepicker'>
{{ form.transferred_on }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.party.name }}" class="control-label col-xs-4">{{ form.party.label }}</label>
<div class="col-xs-8">
{{ form.party }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_amount.name }}" class="control-label col-xs-4">Amount</label>
<div class="col-xs-8">
{{ form.transferred_amount }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_roi.name }}" class="control-label col-xs-4">Interest</label>
<div class="col-xs-8">
{{ form.transferred_roi }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_remark.name }}" class="control-label col-xs-4">Remark</label>
<div class="col-xs-8">
{{ form.transferred_remark }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="btn-toolbar" align="middle">
<button type="submit" class="btn btn-primary btn-color btn-bg-color">Submit</button>
<button type="button" class="btn btn-danger btn-color btn-bg-color" onclick="window.close()">Close</button>
</div>
<!-- /DIV -->
</form>
如果您没有将模型实例传递给表单,它只会呈现初始值。试试这个:
p = Packet.objects.filter(transferred_on__isnull=True)[0]
# or simply
p = Packet()
f = TransferPacketForm(instance=p)
print(f['transferred_on'])
该字段没有初始值,但如果您这样做:
f = TransferPacketForm()
print(f['transferred_on'])
会的。看看吧。
编辑
当您将 initial
字典传递给表单时它不适用,它实际上会检查模型的字段是否为空并使用字典中的值。因此,您的解决方法不是使用字段的 initial
,而是使用表单的 initial
,即通过视图的 get_initial()
。