<here all loading of static , template_filters, crispy_forms >
<form>
{% for i in artifact_length %}
{% with artifact_name="artifact"|artifact_name:forloop.counter0 %}
{{form.artifact_name|as_crispy_field}}
{% endwith %}
{%endfor%}
</form>
這是相關的模板代碼。在這里我要渲染的名稱表單域artifact_0,artifact_1從表單來的。artifact_name里面的變數with作業正常并回傳預期的識別符號artifact_0,artifact_1但我想將這些變數用作表單欄位以呈現為as_crispy_field. 該代碼{{form.artifact_name|as_crispy_field}}不列印任何內容,因為它假設表單為名稱artifact_name不是的欄位。相反,我想在這里使用變數的值。
forms.py
class Someform(forms.form):
def __init__(self, artifact_obj):
super().__init__()
count = 0
for artifact in artifact_obj:
self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput())
count = 1
tags.py
@register.filter('artifact_name')
def get_artifact_name(artifact_prefix: str, counter: int):
print('method', 'prefix', artifact_prefix, 'counter', counter)
return f'{artifact_prefix}_{counter}'
正在創建可變長度表單。就像forms.py正在創建的表單欄位一樣artifact_count,count 的范圍可以從 0 到 obj 的 len。
uj5u.com熱心網友回復:
為此,您不需要使用過濾器/模板標簽等。最簡單的解決方案是遍歷表單欄位以呈現它們:
<form>
{% for field in form %}
{{ field|as_crispy_field }}
{%endfor%}
</form>
這將遍歷表單中的所有欄位。
如果您特別關心這些欄位的順序,您可以呼叫 formsorder_fields方法:
class Someform(forms.form):
def __init__(self, artifact_obj, *args, **kwargs):
super().__init__(*args, **kwargs)
for count, artifact in enumerate(artifact_obj):
self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput())
self.order_fields(["field_1", "field_2", ...] [f"artifact_{i}" for i, _ in enumerate(artifact_obj)] [..., "field_n"])
如果您特別想單獨呈現其他欄位,您可以向表單添加一個方法,該方法將允許您遍歷這些欄位:
class Someform(forms.form):
def __init__(self, artifact_obj, *args, **kwargs):
super().__init__(*args, **kwargs)
for count, artifact in enumerate(artifact_obj):
self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput())
self.artifact_length = len(artifact_obj)
def artifact_fields(self):
return [self[f'artifact_{i}'] for i in range(self.artifact_length)]
然后在模板中回圈這些:
<form>
{% for field in form.artifact_fields %}
{{ field|as_crispy_field }}
{%endfor%}
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367918.html
標籤:姜戈 django-views django-forms django-模板 django-模板过滤器
