[Django]-Django ModelForm initial or custom field value

7👍

There’s a few ways:

  • If in your model you set a default value, afaik it will be used as initial value in the corresponding ModelForm
  • Or just pass an initial dictionary to the form’s initialiser:
    form = OppDetaljiForm(instance=opp_locked, initial={'status': 'odlozen'})
    

Note however that since you’re passing an instance (opp_locked), the value taken from the instance supersedes the value from initial.

The initial value you’re talking about is the value of the field shown to the user in the form when the user hasn’t selected anything to start with. That’s different than overriding the value after the user submits the form (ignoring the user input). You can do that in the form’s clean method for the field:

# in OppDetaljiForm
def clean_status(self):
    status = self.cleaned_data.get('status')
    if not status:
        status = 'odlozen'
    return status

Finally, if the user cannot set the status anyway, then don’t put it in the form at all (remove it from fields and from your template altogether) and set it in your view before saving the model:

if form.is_valid():
    opp_detail = form.save(commit=False)  # gives you the instance without saving it
    opp_detail.status = 'odlozen'  # add values that your form didn't set
    opp_detail.save()  # now save

Or let the form handle it:

class OppDetaljiForm(forms.ModelForm):
     status = 'odlozen'
     class Meta:
         fields = (<list of fields without 'status'!>)
     # ...
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.instance.status = self.status  # assigns the status to the instance

You say you have six forms, if the only difference is which status they set, then just make one form and pass the status to the init method so in your view you can do form = MyForm(request.POST, instance=..., status='odlozen') for example.

Leave a comment