DateField setting default date

I would think this would be an easy solution, but as I am finding, there are a lot of proposed solutions, but none have worked in my case.

I have a DateField on a form where I am trying to have the current date be the default date.

Here is the code in the form.

        today = date.today()
        self.fields['dateinstalled'] = forms.DateField(initial=today, required=True,
                                                     widget=DateInput(attrs={'type': 'date', 'style': 'width:200px'}))                                                       

Through the debugger I can confirm that today does hold the current date.

When the form is displayed, I get the datepicker, but it is blank.
DefaultingDate

The strange thing is that I use this identical code in another form where I set a date and the default does appear.

        today = date.today()
        self.fields['change_date'] = forms.DateField(initial=today, required=True,
                                                     widget=DateInput(attrs={'type': 'date', 'style': 'width:200px'}))

When this form is displayed, the change date shows the current date.

Where should I look to debug and correct this?

Thanks!
BH

We’d need to see more context around this to try and identify the difference(s) between these situations. At a minimum, we’d need to see the forms. We may also need to see the views using them.

Here is the UpdateLogEntry form…

class UpdateLogEntryForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ModelForm, self).__init__(*args, **kwargs)
        self.fields['change_date'] = forms.DateField(widget=DateInput(attrs={'style': 'width:200px', }))
        self.fields['change_note'].widget.attrs.update({'class': 'form-control'})
        self.fields['binary_only'].widget.attrs.update({'class': 'form-check-input'})
        self.fields['form_name'].widget.attrs.update({'class': 'form-control'})
        self.fields['module_category'] = ModuleSelectorModelChoiceField(queryset=Modules.objects.all(),
                                                                        empty_label='(select module)',
                                                                        widget=forms.Select(
                                                                            attrs={'style': 'width:300px'}, ))
        today = date.today()
        self.fields['dateinstalled'] = forms.DateField(initial=today, required=True,
                                                     widget=DateInput(attrs={'type': 'date', 'style': 'width:200px'}))
        self.fields['installed'].widget.attrs.update({'class': 'form-check-input'})
        self.fields['installed'].initial = True

    class Meta:
        model = ChangeLogEntries
        fields = ['change_date', 'change_note', 'module_category', 'binary_only', 'form_name',
                  'dateinstalled', 'installed']
        widgets = {
            'change_note': Textarea(attrs={'rows': '6', 'cols': '80'}),
        }

    def clean(self):
        super(UpdateLogEntryForm, self).clean()

        installed_status = self.cleaned_data.get('installed')
        installed_date = self.cleaned_data.get('dateinstalled')
        if not installed_status:
            self.errors['installed'] = self.error_class(['Installed must be checked.'])

        return self.cleaned_data

Here is the UpdateLogEntry View…

def updatelogentry(request, logentry_id=None):
    log_entry = get_object_or_404(ChangeLogEntries, id=logentry_id)
    log_entry.installed = True
    log_entry.change_date = date.today()
    error_msg = ""
    heading = "Update Log Entry"
    if request.method == 'POST':
        try:
            form = UpdateLogEntryForm(request.POST, instance=log_entry)
            if form.is_valid():
                form.save()
                log_entries = ChangeLogEntries.objects.filter(installed=False).order_by('-change_date').select_related(
                    'module_category')
                return render(request, 'main/updatestatus.html', {"change_list": log_entries})
            else:
                error_msg = form.errors
                return render(request, 'main/updatelogentry.html',
                              {'form': form, 'log_entry': log_entry, "error_msg": error_msg,
                               "heading": heading})
        except ValueError:
            error_msg = "Invalid entry"
            return render(request, 'main/updatelogentry.html', {"log_entry": log_entry,
                                                                "error_msg": error_msg,
                                                                "heading": heading})
    else:
        form = UpdateLogEntryForm(instance=log_entry)
        return render(request, 'main/updatelogentry.html',
                      {"log_entry": log_entry, "form": form, "error_msg": error_msg,
                       "heading": heading})

Here is the CreateLogEntry form…

class CreateLogEntryForm(forms.ModelForm):
    class Meta:
        model = ChangeLogEntries
        fields = ['change_date', 'change_note', 'module_code', 'binary_only', 'form_name', 'module_category']

    def __init__(self, *args, **kwargs):
        super(ModelForm, self).__init__(*args, **kwargs)
        today = date.today()
        self.fields['change_date'] = forms.DateField(initial=today, required=True,
                                                     widget=DateInput(attrs={'type': 'date', 'style': 'width:200px'}))
        self.fields['change_note'].widget = Textarea(attrs={'rows': '6', 'cols': '80'})
        self.fields['module_category'] = ModuleSelectorModelChoiceField(queryset=Modules.objects.all(),
                                                                        empty_label='(select module)',
                                                                        widget=forms.Select(
                                                                            attrs={'style': 'width:300px'}, ))
        self.fields['module_code'] = forms.CharField(label="Module Code", required=False, initial="N/A", max_length=5)
        self.fields['form_name'] = forms.CharField(label="Form/Class Name", required=False, initial="", max_length=50)

    def clean(self):
        super(CreateLogEntryForm, self).clean()

        # get the change note from the data
        change_note = self.cleaned_data.get('change_note')
        if len(change_note) < 5:
            self.errors['change_note'] = self.error_class(['The change note requires a minimum of 5 characters.'])

        # the form name must have at least 5 characters in order to be valid
        form_name = self.cleaned_data.get('form_name')
        self.cleaned_data['module_code'] = 'N/A'
        if len(form_name) > 0:
            if len(form_name) < 5:
                self.errors['form_name'] = self.error_class(
                    ['The form name if specified, must be at least 5 characters.'])
            # if the binary-only field is checked, then we should not have a form name
            binary_only = self.cleaned_data.get('binary_only')
            if binary_only:
                self.errors['binary_only'] = self.error_class(
                    ['If Binary-Only is checked, you should not specify a form name.'])

        return self.cleaned_data

Here is the CreateLogEntry view…

def createlogentry(request):
    if request.method == 'POST':
        form = CreateLogEntryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
        else:
            print(form.errors)
            return render(request, 'main/createlogentry.html', {'form': form})
    else:
        form = CreateLogEntryForm()
    return render(request,
                  'main/createlogentry.html',
                  {'form': form
                   })

Let me know if you need to see anything else.

Thanks!
BH

So which one is which based upon your original post? Is it that the updatelogentry field is not showing the date where createlogentry is?

Also, can you confirm that the field showing this behavior in updatelogentry is the dateinstalled field, while the field you’re referring to in createlogentry is change_date?

Side note: For your tests in your form, tests that only examine one field should be in a clean_<fieldname> function and not all combined in your general clean method.
It’s “cleaner” that way. (bad-pun intended.)

Yes, the dateinstalled field is not showing the date, and createlogentry is.

Also, dateinstalled is the field referred to in updatelogentry. If I select a date and then save, the dateinstalled field in the DB has the correct value.

I wanted to update this post as fixed, as I was able to figure this out. After taking a break, I realized I was setting the default date for the wrong field.

All is good now!