django ModelForm DateField初始值不起作用

时间:2015-02-15 07:49:52

标签: html django django-forms django-templates django-views

我想在我的ModelForm中为日期字段设置初始数据,但它不起作用。以下是我的代码。

def get_date():
    return timezone.localtime(timezone.now()).date()

的ModelForm:

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">&times;</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>

1 个答案:

答案 0 :(得分:1)

如果没有传递给表单的模型实例,它将只呈现初始值。试试这个:

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()