开发者

Django Forms - set field values in view

开发者 https://www.devze.com 2023-03-04 05:29 出处:网络
I ha开发者_如何学运维ve 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

I ha开发者_如何学运维ve 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


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'})
    ...
0

精彩评论

暂无评论...
验证码 换一张
取 消