Reputation: 231
When I am about to create a model instance via the UI, I'd like to default a field (let's say 'status' to value 'draft'). I tried to do this in the Form in `init(): ** Model**
class ForecastConfiguration(Control):
uuid = kp.ObjectIDField()
name = kp.ObjectNameField()
description = kp.ObjectDescriptionField()
status = models.ForeignKey(Status, blank=False, null=False, editable=True, on_delete=models.PROTECT)
Form
class ForecastConfigurationCreateForm(forms.ModelForm):
class Meta:
model = ForecastConfiguration
exclude = ['uuid', 'hierarchy_nodes']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# default status
self.fields['status'] = ModelChoiceField(queryset=ObjectStatus.get_object_status_list(self, is_form=True))
# status is defaulted when created; will get updated by planning element status
self.fields['status'].widget.attrs['disabled'] = True
This works fine: the value is defaulted. However, when I submit the form I get a validation error saying that this field cannot be empty and in the form, the value is empty.
I tried doing this in the view as well (same result):
View
class ForecastConfigurationCreateView(CreateView):
model = ForecastConfiguration
form_class = ForecastConfigurationCreateForm
template_name = 'frontend/base/planning_create.html'
object = None
# success_url = ''
def get(self, request, *args, **kwargs):
# default status to 'Draft'
status_id = Status.objects.get(name=constant.status['draft']).uuid
form = ForecastConfigurationCreateForm(initial={'status': status_id})
member_formset = MemberFormSet()
return render(request, self.template_name, {'form': form, 'member_formset': member_formset})
Edit
This is how the status
field is defaulted when loading:
After saving, the value is still there but the form complains:
Using readonly
as the attribute makes the field read-only but it still can be edited:
Upvotes: 0
Views: 665