Django中带有Datatime字段的ValidationError

2024-05-04 12:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Django项目中与{}的{}一起工作。模板的日期选择器链接:Doc

在我的models.py中:

class Industry(models.Model):
    name = models.CharField(max_length=200, blank=True)
    mycustomdate = models.DateTimeField(null=True, blank=True)

在我的template中:

<form method="post" class="row m-0">
  {% csrf_token %}
    <div class="form-group">
      <label>Industry Name</label>
      <input type="text" class="form-control" name="name" placeholder="Type industry name">
    </div>
    <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
      <input type="text" class="form-control datetimepicker-input" name="mycustomdate" data-target="#datetimepicker1"/>
      <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
      </div>
    </div>
  <a href="#" class="ml-auto mr-3 my-4"><button type="submit" class="btn btn-primary">Submit</button></a>
</form>

<script>
  $(function () {
    $("#datetimepicker1").datetimepicker();
  });
</script>

在我的views.py中:

if request.method == "POST":
  this_mycustomdate = request.POST['mycustomdate']

  print(this_mycustomdate)

  Industry_obj = Industry.objects.create(name=this_name, mycustomdate = this_mycustomdate)
  Industry_obj.save()

但上面说的错误是:

ValidationError at /industrySignup/
['“03/04/2021 5:06 PM” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

用这句话:

Industry_obj = Industry.objects.create(name=this_name, mycustomdate = this_mycustomdate)

我怎样才能解决这个问题


Tags: textnamedivformtrueinputdatamodels
1条回答
网友
1楼 · 发布于 2024-05-04 12:24:46

首先,您的日期字符串周围似乎有一些特殊的引号字符,请删除它们:

this_mycustomdate = this_mycustomdate.strip('“”') # Note these are not the normal double quotes

接下来,将字符串转换为datetime实例:

from datetime import datetime

this_mycustomdate = datetime.strptime(this_mycustomdate, "%d/%m/%Y %I:%M %p") # I have considered the format of the date as DD/MM/YYYY

在这之后你应该可以走了

相关问题 更多 >