我的新闻应用中有一个end_date字段,这是一个兼容性字段。 当作者正在编辑其中一个新的并删除end_date时,我在模型中将end_date设置为None。
我的问题是该字段然后在下次编辑时显示值“无”而不是空白。
这是我的领域:
models.py
end_date = models.DateTimeField(null=True, blank=True)
forms.py
end_date = forms.CharField(label='', required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'format': 'DD, d MM yy', 'placeholder': _('End date')}))
和我视图中的分配:
views.py
if news_form.cleaned_data['end_date'] == '' :
edited_new.end_date = None
edited_new.save()
编辑:
这是我的模板:
news.html
<form action="#" method="post" role="form" id="news-form">{% csrf_token %}
{{ news_form.media }}
<div class="col-xs-12">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12 col-md-6">
<h2 class="panel-title">{% trans "Add or edit news" %}</h2>
</div>
<div class="col-xs-12 col-md-6">
<div class="pull-right">
<a href="#" class="btn btn-secondary cancel"><span class="glyphicon glyphicon-floppy-remove"></span> {% trans "Cancel" %}</a>
<button type="submit" class="btn btn-primary form-btn save"><span class="glyphicon glyphicon-floppy-saved"></span><span class="button-text"> {% trans "Save" %}</span></button>
</div>
</div>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6">
{{ news_form.title }}
</div>
<div class="col-xs-4 col-md-2">
{% trans 'Tag' %}
</div>
<div class="col-xs-8 col-md-4">
{{ news_form.tag }}
</div>
</div>
<div class="row">
<div class="col-xs-12 no-label-field redactor-field">
{{ news_form.message }}
</div>
</div>
<div class="row">
<div class="col-xs-6 date-field no-label-field">
<div class="form-group">
<div class='input-group date datetimepicker'>
{{ news_form.start_date }}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-xs-6 date-field no-label-field">
<div class="form-group">
<div class='input-group date datetimepicker'>
{{ news_form.end_date }}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ news_form.active }} {% trans 'Activate the news' %}
</div>
</div>
</div>
</div>
</div>
<span style="display:none;">{{ news_form.id }}</span>
</form>
答案 0 :(得分:11)
您可以使用自Django 1.3以来可用的过滤器default_if_none
,它仅适用于None
的值。
{{ news_form.end_date|default_if_none:'' }}