Reputation: 53
I have a form that I want to submit date as mm/yyyy
.
class Add_Serv(forms.Form):
month_add = forms.ChoiceField(required=True, choices=['01','02'])
year_add = forms.ChoiceField(required=True,
choices=[(x, x) for x in xrange(date.today().year - 1, date.today().year + 1)])
When my month prints out in form, it's only one digit integer 1
instead of 01
. It doesn't sound like a big deal but it screws up my date format when handling these dates (and also looks very ugly). Is there any way to keep that zero before the number?
Upvotes: 0
Views: 509
Reputation: 2294
use jquery library
You need only one field. forms.py
class FormA(forms.Form):
fecha = forms.DateField(input_formats=['%m/%Y'])
views.py
def formulario(request):
if request.method == "POST":
form = FormA(request.POST)
if form.is_valid:
# action
else:
form = FormA()
return render(request,"add.html",{'form':form})
Your template I add bootstrap css library and django-bootstrap-from
<div class="row">
<div class="col-lg-8">
<form id="form" action="" method="POST">
{{form|bootstrap_horizontal}}
{%csrf_token%}
<p align="right"><button id="enviar" type= 'submit' class="btn btn-success"> Guardar</button>
<button type= "reset" class="btn btn-warning"> Limpiar</button></p>
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('#id_fecha').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
The result http://prntscr.com/7qd01v
Upvotes: 0
Reputation: 1991
Print it out using format
:
print("{:02d}".format(my_number))
See Pyformat for more formatting tips
Upvotes: 1
Reputation: 1285
add validation in form's clean method and check if the length of month field is 1 or 2.
Append 0 before if length is 1 and return value of month
Upvotes: 1