How to add default value for Date Picker in Django Model Form

Viewed 25

Currently I have a date picker in a django model form that works perfectly fine. However, I want to add an initial (default) value to it. Here is my current code :

class DatePickerInput(forms.DateInput):
        input_type = 'date'
        
class PDFClassificationForm(forms.ModelForm):  
    
    class Meta:  
        model = Documents
        fields = [
                  'id_documenttype',
                  'dateenvoi',,
                  'comment']
        widgets = {
            'dateenvoi' : DatePickerInput(),
        }

I tried adding initial as a parameter to DatePickerInput() like so :

widgets = {
            'dateenvoi' : DatePickerInput(initial= datetime.now().strftime('%d/%m/%y %H:%M:%S')),
        }

However it was unsuccessful, any suggestions ?

1 Answers

Try this:

import datetime
    
class PDFClassificationForm(forms.ModelForm):  
    
    class Meta:  
        model = Documents
        fields = [
              'id_documenttype',
              'dateenvoi',
              'comment',
               ]
        widgets = {
            'dateenvoi' : DatePickerInput(widget=forms.TextInput(attrs={'value': datetime.now().strftime('%d/%m/%y %H:%M:%S')})),
        }
        
Related