Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms - set field values in view

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

like image 298
Garfonzo Avatar asked May 07 '11 21:05

Garfonzo


1 Answers

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'})
    ...
like image 71
Alasdair Avatar answered Sep 23 '22 08:09

Alasdair