Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

python - ValidationError with Datatime field in Django

I am working with the date picker of Tempus Dominus Bootstrap 4 in my Django project. template's date-picker link: Doc

in my models.py:

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

in my 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>

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

But it says error like:

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

with the line:

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

How can I solve this problem?

question from:https://stackoverflow.com/questions/65941808/validationerror-with-datatime-field-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly you appear to have some special quote characters around your date string, remove them:

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

Next convert your string into a datetime instance:

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

After this you should be good to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...