我遇到了问题,无法弄清楚如何解决问题。
我的申请表中有以下表格:
class ContentForm(ModelForm):
class Meta:
model = Content
fields = ('url_1','url_2','url_3','url_4','url_5',)
widgets = {
'url_1': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
'url_2': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
'url_3': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
'url_4': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
'url_5': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
}
我尝试做的是通过循环动态生成这些url字段。我采用了this方法(实现了动态属性查找的模板标记):
{% for i in 12345|make_list %}
{% with url='url_'|add:i %}
{{ form|getattribute:url }}
{% endwith %}
{% endfor %}
然而它无法正常工作。 Django没有渲染输入字段,并抱怨我的表单对象没有一个名为url_1
的属性。如果我直接调用同一表单的url_1
属性,则可以正常工作。
getattribute
模板代码的实施与here相同。
[更新:发布我的代码]
views.py
@login_required
def new(request):
form = ContentForm()
return render(request, "new.html", {'form': form})
new.html
<form action="{% url 'create_content' %}" method="POST">
...
{% include 'partials/urls.html' %}
...
</form>
urls.html
{% load getattribute %}
{% for i in 12345|make_list %}
{% with url='url_'|add:i %}
<label>URL {{i}}</label>
{{ form|getattribute:url }}
{% endwith %}
{% endfor %}
getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
return getattr(value, arg)
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
ps。:django版本运行是1.9.2
答案 0 :(得分:2)
更改getattribute.py
,如下所示:
import re
from django.forms import Form, ModelForm
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
elif issubclass(value.__class__, (Form, ModelForm)) and arg in value.fields:
return value[arg]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
你可以看到第17和第18行预期的特殊条件,与表格相关并返回相关的渲染小部件;)