Django Forms - set field values ​​in view

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

I don’t want to just exclude these fields from the modelForm class, because it might be necessary for the user to edit these values ​​along the way.

Any help?

thanks

+7
source share
1 answer

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

 # models.py from datetime import date class WorkOrder(models.Model): ... dateWOCreated = models.DateField(default=date.today) 

To display dates in MM/DD/YYYY format, you need to redefine 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 default analog argument is the original argument. For other fields, you may need to dynamically calculate the initial field value in the view. I gave an example below. See the Django Docs for Dynamic Initial Values for more information .

 # 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'}) ... 
+6
source

All Articles