我不想用字段的当前值自动填充ProjectForm字段,即:
class ProjectForm(forms.ModelForm):
project_name = forms.CharField(label='Project Name', widget=forms.TextInput(attrs={'placeholder': 'fixed_value'}))
但是,我希望使用当前项目名称(如果适用)预填充字段而不是固定值。
答案 0 :(得分:0)
如果你的视图中有项目/对象,你可以这样做:
forms.py
:
class ProjectForm(forms.ModelForm):
project_name = forms.CharField(label='Project Name', widget=forms.TextInput(attrs={'placeholder': 'fixed_value'}))
class Meta:
model = Project
fields = ['project_name']
def __init__(self, *args, **kwargs):
placeholder = kwargs.pop("dynamic_placeholder")
super().__init__(*args, **kwargs)
self.fields['project_name'].widget.attrs['placeholder'] = placeholder
views.py
:
class YourView(FormView):
form_class = ProjectForm
def get_form_kwargs(self):
form_kwargs = super().get_form_kwargs()
form_kwargs['dynamic_placeholder'] = 'dynamic_value_queried_by_orm'
return form_kwargs
我不确定你的意思是' autopopulating'。您以placeholder
属性为例,但也许您想使用initial
代替?
self.fields['project_name'].initial = placeholder
但是为什么你没有使用UpdateView
?