8

I have a model which represents a work order. One of the fields is a DateField and represents the date the work order was created (aptly named: dateWOCreated). When the user creates a new work order, I want this dateWOCreated field to be automatically populated with todays date and then displayed in the template. I have a few other fields that I want to set without user's intervention but should show these values to the user in the template.

I don't want to simply exclude these fields from the modelForm class because there may be a need for the user to be able to edit these values down the road.

Any help?

Thanks

1 Answer 1

7

When you define your model, you can set a default for each field. The default object can be a callable. For your dateWOCreated field we can use the callable date.today.

# models.py
from datetime import date

class WorkOrder(models.Model):
    ...
    dateWOCreated = models.DateField(default=date.today)

To display dates in the format MM/DD/YYYY, you need to override the widget in your model form.

from django import forms
class WorkOrderModelForm(forms.ModelForm):
    class Meta:
        model = WorkOrder
        widgets = {
            'dateWOCreated': forms.DateInput(format="%m/%d/%Y")),
        }

In forms and model forms, the analog for the default argument is initial. For other fields, you may need to dynamically calculate the initial field value in the view. I've put an example below. See the Django Docs for Dynamic Initial Values for more info.

# views.py
class WorkOrderModelForm(forms.ModelForm):
    class Meta:
        model = WorkOrder

def my_view(request, *args, **kwargs):
    other_field_inital = 'foo' # FIXME calculate the initial value here  
    form = MyModelForm(initial={'other_field': 'other_field_initial'})
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

Sweetness, that looks like it will work for me. However, I have a follow up question. If I use the default=date.today method, it will give a value of YYYY-MM-DD. I need to change this to MM/DD/YYYY. I tried date.today().strftime(%m\/%d\/%Y) but django does not like this. Any ideas?
Nevermind, Django is OK with my YYYY-MM-DD formatting. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.