简体   繁体   中英

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)
        # }

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',
        ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM