【问题标题】:How to make Date fields in models not required using in html input type=date如何在 html 输入类型 = 日期中使用不需要的模型中的日期字段
【发布时间】:2019-08-23 05:35:04
【问题描述】:

这就是我所拥有的:

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'] 
        )

文件.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: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]

我该如何解决?

【问题讨论】:

  • 在日期的输入标签中,我怀疑 / 结束时 > 是否有帮助。如果这和 Cesar17 的答案都没有帮助,那么也许出于测试目的,请尝试在输入标记中包含 formnovalidate 以查看验证错误是否存在于实现中而不是输入中。

标签: django django-models datefield


【解决方案1】:

如果您不需要在首次创建时添加日期,则应使用“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

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2020-09-07
    • 2019-12-21
    • 2015-10-18
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多