1

That's what I have:

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> 

As you can see in models date field can be empty. But if I run it without filling the date field I get an error:

django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]

How I can fix it?

1
  • in the date's input tag, i doubt that / by the closing > is helping. if neither that nor Cesar17's answer are helpful then perhaps for testing purposes try include formnovalidate in the input tag to see if the validation error is present in the implementation rather than the input.
    – ocæon
    Apr 2, 2019 at 17:34

1 Answer 1

0

If you don't need to add the date when it is first created, then you should specify that it is not required with "auto_now_add=False". Please consider reading the source:

models.py

date_of_purchase = models.DateField(blank=True, null=True,auto_now_add=False)

Source https://docs.djangoproject.com/en/2.1/ref/models/fields/#datetimefield

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.