简体   繁体   English

自定义模板

[英]Custom Templating

I want to customize the default form template rendering that GAE does when using its version of Django. 我想自定义GAE在使用其Django版本时所做的默认表单模板呈现。 I'm using Django 1.3 in GAE. 我在GAE中使用Django 1.3。

I have an "input" page that loads app engine templates and calls a "parameters" module that defines the form inputs. 我有一个“输入”页面,可加载应用程序引擎模板并调用定义表单输入的“参数”模块。 Here is the middle of the input page that renders the form: 这是呈现表单的输入页面的中间部分:

html = html + template.render(templatepath + '04input_start.html', {})
html = html + str(model_parameters.ModelInp())

Here is model_parameters.ModelInp(): 这是model_parameters.ModelInp():

class ModelInp(forms.Form):
    activeIngredient = forms.CharField(widget=forms.Textarea (attrs={'cols': 20, 'rows': 1}), label='Active Ingredient')
    expDuration = forms.ChoiceField(required=True, label='Exposure Duration', choices=expDuration_CHOICES, initial='Intermediate-Term')

The result is a HTML form where each variable above is table row with the label as 1 column and the CharField/ChoiceField as the other 1 column. 结果是HTML表单,其中上面的每个变量都是表行,标签为1列,而CharField / ChoiceField为其他1列。 Essentially: 实质上:

<tr>
    <th>
        <label for="id_activeIngredient">Active Ingredient:</label>
    </th>
    <td>
        <textarea rows="1" cols="20" name="activeIngredient" id="id_activeIngredient"></textarea>
    </td>
</tr>
<tr>
    <th>
        <label for="id_expDuration">Exposure Duration:</label>
    </th>
    <td>
        <select name="expDuration" id="id_expDuration">
            <option value="0">Short-Term</option>
            <option value="1">Intermediate-Term</option>
            <option value="2">Long-Term</option>
        </select>
    </td>
</tr>

How would I go about rendering this form in a custom Django template to format the form in a different format other than the simple 2 column default? 我将如何在自定义Django模板中呈现此表单,以将表单的格式设置为默认的简单2列以外的其他格式?

GAE doesn't do any "default template rendering". GAE不执行任何“默认模板渲染”。 This is all Django. 这就是Django。

You are doing something very bizarre in that snippet from the view. 从视图的角度来看,您正在做一些非常奇怪的事情。 The whole point of templates is that you build up the entire HTML page within the template. 模板的全部目的是在模板中构建整个HTML页面。 Why are you concatenating different bits of HTML together in the view? 为什么在视图中将HTML的不同位连接在一起? That defeats the purpose of using templates. 这违反了使用模板的目的。

Instead of simply concatenating the string representation of the template, you should pass the instantiated form to the template context. 而不是简单地串联模板的字符串表示形式,您应该将实例化的表单传递给模板上下文。 Then you can iterate over its fields, or specify them all individually so that you can wrap them in whatever layout you like. 然后,您可以遍历其字段,或者分别指定它们的全部,以便可以将它们包装在所需的任何布局中。 This is all well discussed in the Django docs for displaying a form in a template . 在Django文档中已经讨论了所有有关在模板中显示表单的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM