如何使用 Django 模板编辑表单字段以添加一些条件
How to edit a form field to add some condition using Django template
我有一个表格(ModelForm
、Model
和 view
)。
一切正常,但项目中有一个新需求,其中一个文本输入不再简单,我需要使用一些 Django 模板 (if condition
)。
这正是我需要的输入的 HTML 表示(它单独工作):
<input class="form-control project" id="project" name="project" type="text" {% if entry.project %}value="{{ entry.project.id }}: {{ entry.project.name }}"{% endif %}>
我尝试过的:
- 编辑
forms.py
中小部件的属性,使其看起来尽可能接近上面的 HTML 代码,但这对我来说是不可能的。
已更新@bdbd [已解决]
提供的解决方案
forms.py
:
class ExpenseForm(ModelForm):
class Meta:
model = Expense
fields = ['project']
widgets = {
'project': forms.TextInput(
attrs={
'class': 'form-control ts_project',
'id': 'ts_project',
'name': 'ts_project',
}
),
}
def __init__(self, *args, **kwargs):
entry = kwargs.pop('entry')
super().__init__(*args, **kwargs)
if entry:
self.fields['project'].widget.attrs.update({'value': entry.project})
该代码不起作用,但我想不出另一种方法让它起作用。如果我删除 value
和所有 Django 模板代码,class, id and name
将按预期工作。
如何通过 Django 模板向 Django 表单的小部件/字段添加条件?
在您的 ExpenseForm
中,您可以使用 __init__
.
根据一些任意标准修改小部件的属性
例如,假设您在表单中传递了一个 entry
对象,并且您想要修改基于该对象的小部件:
class ExpenseForm(ModelForm):
...
def __init__(self, *args, **kwargs):
entry = kwargs.pop('entry')
super().__init__(*args, **kwargs)
if entry:
self.fields['project'].widget.attrs.update({'value': entry.project})
我有一个表格(ModelForm
、Model
和 view
)。
一切正常,但项目中有一个新需求,其中一个文本输入不再简单,我需要使用一些 Django 模板 (if condition
)。
这正是我需要的输入的 HTML 表示(它单独工作):
<input class="form-control project" id="project" name="project" type="text" {% if entry.project %}value="{{ entry.project.id }}: {{ entry.project.name }}"{% endif %}>
我尝试过的:
- 编辑
forms.py
中小部件的属性,使其看起来尽可能接近上面的 HTML 代码,但这对我来说是不可能的。
已更新@bdbd [已解决]
提供的解决方案forms.py
:
class ExpenseForm(ModelForm):
class Meta:
model = Expense
fields = ['project']
widgets = {
'project': forms.TextInput(
attrs={
'class': 'form-control ts_project',
'id': 'ts_project',
'name': 'ts_project',
}
),
}
def __init__(self, *args, **kwargs):
entry = kwargs.pop('entry')
super().__init__(*args, **kwargs)
if entry:
self.fields['project'].widget.attrs.update({'value': entry.project})
该代码不起作用,但我想不出另一种方法让它起作用。如果我删除 value
和所有 Django 模板代码,class, id and name
将按预期工作。
如何通过 Django 模板向 Django 表单的小部件/字段添加条件?
在您的 ExpenseForm
中,您可以使用 __init__
.
例如,假设您在表单中传递了一个 entry
对象,并且您想要修改基于该对象的小部件:
class ExpenseForm(ModelForm):
...
def __init__(self, *args, **kwargs):
entry = kwargs.pop('entry')
super().__init__(*args, **kwargs)
if entry:
self.fields['project'].widget.attrs.update({'value': entry.project})