这就是我所拥有的:
models.py
class Comic(models.Model):
title = models.CharField(max_length=255, blank=False)
date_of_purchase = models.DateField(blank=True, null=True)
views.py
def add_to_my_collection(request):
if request.method == 'POST':
comic = Comic.objects.create(
title = request.POST['title'].capitalize(),
date_of_purchase = request.POST['date_of_purchase']
)
file.html
<form class="create_edit" action="/add_to_my_collection" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="title">Title:</label>
<input name="title" type="text" class="form-control" id="title" value="{{comic.title}}">
</div>
<div class="form-group">
<label for="date_of_purchase">Date of purchase:</label>
<input name="date_of_purchase" type="date" id="date_of_purchase" class="form-control"/>
</div>
<div class="sub_but">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</form>
正如您在模型中看到的,日期字段可以为空。但是,如果我在不填写日期字段的情况下运行它,则会收到错误消息:
django.core.exceptions.ValidationError:[“”值的日期格式无效。它必须为YYYY-MM-DD格式。“]
我该如何解决?
答案 0 :(得分:0)
如果您不需要在首次创建日期时添加日期,则应使用“ auto_now_add = False”指定不需要日期。请考虑阅读源代码:
models.py
date_of_purchase = models.DateField(blank=True, null=True,auto_now_add=False)
来源 https://docs.djangoproject.com/en/2.1/ref/models/fields/#datetimefield