[Django]-Python/Django date field in html input tag

7👍

The problem is value="{{m.dob|date:'d/m/Y'}}" which must be specified as value="{{m.dob|date:'Y-m-d'}}"

👤HenryM

1👍

Dude, your question is not clear. But for now, I am assuming you are new to Django.

Your DB value is not populating in the template. In order to show the value, you must do two steps:

  • First query the model object
  • Pass it through additional context dictionary from the Django view.
from django.views.generic import View
from django.shortcuts import render

class Home(View):
    template_name = "home.html"
    def __init__(self, **kwargs):
        pass

    def get(self, request):
        # Fetch your object here. ID or any other 
        myObj = MyModel.objects.get(id=1)
        # Third argument is the conext dictionary
        return render(request,self.template_name,{'myObj': myObj})

Now just use that myObj in your template with the following syntax.

<tr><td>Date of Birth</td><td><input type="date" name="DOB" value="{{myObj.dob|date:"d/m/Y"}}" required=True></td></tr>

Here this code is in home.html.

1👍

If using ModelForm and passing that form object to template, then it should be

value="{{m.dob.value|date:'Y-m-d'}}"

0👍

You can use default like so:

date = models.DateField(_("Date"), default="{{"+datetime.date.today+"}}")

0👍

You can just add

`<script>
    window.onload = function(){
        document.getElementById("id_dob").type = "date";
    }
</script>`

in the end of your .html file and you can collect date and time as string

Leave a comment