Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't override the Model Field in Django ModelForm

I'm trying to add a DateTimeWidget and Initial value to the due_date field of my Model, I'm following the documentation as close as I can tell. No matter what I try, I can't get the field declared in my ModelForm class to override my existing field in the Model.

https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#overriding-the-default-fields

If I add a Widget separately it works, but then I don't know how to add an initial value unless I set the default in the model. Can someone point out what I'm doing wrong?

from django import forms

import datetime
from datetimewidget.widgets import DateTimeWidget


from .models import EstRequest


def due_date():
    due_date = (datetime.datetime.now() + datetime.timedelta(days=1))
    return due_date


class EstRequestModelForm(forms.ModelForm):

    class Meta:
        model = EstRequest
        due_date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget, initial=due_date)

        fields = [
            'market',
            'plan',
            'builder',
            'due_date',
            'notes',
        ]

        # widgets = {
        #     # Use localization and bootstrap 3
        #     'due_date': DateTimeWidget(attrs={'id': "due_date"}, usel10n=True, bootstrap_version=3)
        # }
like image 203
whieronymus Avatar asked Dec 21 '16 18:12

whieronymus


1 Answers

In fact you are definfing the field in the wrong place, It should be outside Meta class:

class EstRequestModelForm(forms.ModelForm):

    due_date = forms.DateTimeField(widget=forms.DateTimeInput, initial=due_date)

    class Meta:
        model = EstRequest
        fields = [
            'market',
            'plan',
            'builder',
            'due_date',
            'notes',
        ]
like image 76
Dhia Avatar answered Oct 29 '22 13:10

Dhia