我和我的团队正在尝试用Django开发一个“非常动态”的web应用程序。 我们为用户提供了一个“配置”模板,每个人都可以在其中配置自己的空间。 每个配置选项都应该从数据库中读取。你知道吗
查看:
def config(request):
if 'logged' not in request.session:
return redirect(login)
apps_list = App.objects.all()
varS = varsesion(request)
context = Configurations.objects.all()
for row in context:
row.form = eval(row.form) #Not sure at all if this is ok
print (row.form)
context.App = 'config'
return render(request, "index.html", {'context': context, 'apps_list ': apps_list , 'varS': varS,
'context.App': context.App})
在我们的数据库中,我们有这样的Configurations
模型表:
+----+-----+-----+-----+---------+---------------+
| id |user |Title|Body |OptionBtn| form |
+----+-----+-----+-----+---------+---------------+
| N |userA| X | X | X | DataConfig() |
+----+-----+-----+-----+---------+---------------+
| N2 |userA| X | X | X | ColorsConfig()|
+----+-----+-----+-----+---------+---------------+
| N3 |userA| X | X | X |ButtonsConfig()|
+----+-----+-----+-----+---------+---------------+
还有很多我要跳过的专栏。。。你知道吗
当然,DB的form
字段中的每个Form
值都存在于表单.py他们各自的名字。
当我尝试在我们的模板中迭代这些表单字段时,问题就来了(DB中的每一列都会正确地显示,如按钮、标题、文本等)
下面是模板(我跳过了示例表中的一些属性):
<div class="breadcrumb">
<li class="breadcrumb-item">
<a href="/config.html"><h1 style="color:#871830">Configurations panel</h1></a>
</li>
</div>
{% for configuration in context %}
<div style="" id="panel{{ configuration.codConfi }}" class="breadcrumb form-inline">
<div class="form-group col-12" style="color:#228718"><h3>{{ configuration.title}}</h3></div>
<div class="form-group col-3 m-1">
<label class="form-group">{{ configuration.body }}</label>
</div>
<button id="btn{{ configuration.codConfi }}" type="submit" class="btn btn-info ml-auto mr-0 mr-md-3 my-2 my-md-4">{{ configuration.OptionBtn }}</button>
</div>
这一切都恰到好处地展现了出来。但是说到form
DB列。。。你知道吗
<!-- _______________________Forms iterations__________________________ -->
<form style="display:none" id="frm{{ configuration.codConfi }}" class="breadcrumb form-inline" action="/Config/{{ configuration.codConfi }}" method="POST" enctype="application/x-www-form-urlencoded">{% csrf_token %}
<div class="form-group col-12" style="color:#228718"><h3>Configure {{ configuration.Title }}</h3></div>
{% for field in configuration.form %}
<div class="form-group col-3 m-1">
<label class="form-group">{{ field.label }}: </label>
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-success ml-auto mr-0 mr-md-3 my-2 my-md-4">Apply changes</button>
</form>
{% endfor %}
(如果您看到一些属性没有显示在我的示例表中,那只是因为我没有键入所有属性)。你知道吗
它没有正确地显示实际的表单,而是将form
DB列的值显示为字符串。例如,对于form
列(DataConfig()
)中的第一个值,它在迭代中将每个字母显示为字符串(首先显示“D”,然后显示“a”,然后显示“t”,直到最后一个“)”。
我怎样才能告诉Django它不是一个字符串值而是一个变量?你知道吗
在Django模型
Configuration
上,可以添加一个属性来获取和实例化实际的form类。你知道吗例如:
然后,在模板中(假设
configuration
是模型Configuration
的一个实例),您可以更改此行:在这里
注意:要实现这一点,您需要在DB字段中存储不带parethesis的表单类名(或者在调用
getattr(forms_module, self.form)
之前删除parethesis)。你知道吗如果你需要更具体的东西,你需要在你的问题中添加更多的信息。你知道吗
相关问题 更多 >
编程相关推荐