Goun2 Goun2 - 14 days ago 9
Python Question

How to add a datepicker to django forms

Django doesn't support a datepicker for its forms, i didn't find any solution that works for me.

If anyone knows some simple solution for this, i'd be very thankful.

Thanks.

forms.py

class meta:
model = Student
fields = ["classfk","name","birth_date"]


views.py

class CreateNewStudent(CreateView):
fields = ("classfk","name", "birth_date")
model = Student
success_url = '/class/'
template_name = "temp/newstudent.html"


newstudent.html

<html>
<body>
<head>

</head>

<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit"/>
</form>

</body>
</html>

Answer

In case of your example, your form should look like that:

class DateForm(ModelForm):
  class Meta:
    model = Student
    fields = ["classfk","name","birth_date"]

your view.py:

class CreateNewStudent(CreateView):
  fields = ("classfk","name", "birth_date")
  model = Student
  success_url = '/class/'
  template_name = "temp/newstudent.html"

and your template:

<head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
                $(function() {
                        $( "#id_birth_date" ).datepicker({
                                dateFormat: "yy-mm-dd",
                                defaultDate: "+1w",
                                changeMonth: true,
                                numberOfMonths: 2,
                                onClose: function( selectedDate ) {
                                        $( "#id_birth_date" ).datepicker( "option", "minDate", selectedDate );
                                }
                        });
                });
        </script>

<head>
<body>
<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save" />
</form>
</body>

You can customize datepicker according jQuery UI documentation http://api.jqueryui.com/datepicker/

Comments