Format Date to Save Form

6

Good afternoon, I have a view based on Form View:

class CrearPuesto(FormView):
    template_name = 'crear_puesto.html'
    form_class = PuestoForm
    success_url = reverse_lazy('administracion:maestro_puestos')

    def form_valid(self, form):
        form.save()
        return super(CrearPuesto, self).form_valid(form)

The form is as follows:

class PuestoForm(forms.ModelForm):

    class Meta:
        model = Puesto
        fields =['oficina','trabajador','fecha_inicio','fecha_fin','es_jefatura']

    def __init__(self, *args, **kwargs):
        super(PuestoForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
        })
        self.fields['fecha_fin'].required = False
        self.fields['es_jefatura'].required = False

The problem arises when I save dates because the format that users use is d / m / y and I get a "Enter a valid date." My idea is to be able to format the date before saving it but I do not know how to do it. Thank you very much for your help.

    
asked by inkarri 04.05.2016 в 22:28
source

2 answers

2

I solved it, the only thing I had to do was to overwrite the behavior of the 'start_date' field by adding the input_formats argument as follows:

self.fields['fecha_inicio'].input_formats = ['%d/%m/%Y']
    
answered by 04.05.2016 / 23:45
source
0

You can do it with the following command:

import datetime
datetime.datetime.strptime("25/4/16", '%d/%m/%y').strftime('%Y-%m-%d')
    
answered by 04.05.2016 в 22:34