django动态添加表单字段

时间:2014-12-18 15:59:30

标签: django forms dynamic

基于this我想写一个动态模板,我可以动态地添加选择宽度的表单。

型号:

class TodoList(models.Model):
    SEC = 'section'
    DIV = 'div'
    SECCHOICES = (
        (SEC, "Section"),
        (DIV, "Div"),
    )
    tag = models.CharField(max_length=20, choices=SECCHOICES, default=SEC)

    def __unicode__(self):
        return self.name


class TodoItem(models.Model):
    COL16 = '16'
    COL25 = '25'
    COL33 = '33'
    COL50 = '50'
    COL66 = '66'
    COL75 = '75'
    COL100 = '100'
    CHOICES = (
        (COL16, "16%"),
        (COL25, "25%"),
        (COL33, "33%"),
        (COL50, "50%"),
        (COL66, "66%"),
        (COL75, "75%"),
        (COL100, "100%"),
    )
    width = models.CharField(max_length=3, choices=CHOICES, default=COL100)
    list = models.ForeignKey(TodoList)

    def __unicode__(self):
        return self.name + " (" + str(self.list) + ")"

查看:

def post_list(request):
    posts = TodoItem.objects.order_by('id')
    return render(request, 'blog/post_list.html', {'posts': posts})

模板:

{% for post in posts %}
    <{{ post.list.tag }}>
        <div class="column{{ post.width }}" >
        </div>
    </{{ post.list.tag }}>
{% endfor %}

输出是:

Section:col,Section:col,Section:col,Section:col

我希望:

部分:col,col,col,col

对任何想法感到高兴,抱歉,如果有些事情太愚蠢 - 我对django / python来说很新

1 个答案:

答案 0 :(得分:0)

你可以这样做吗?

<{{ post.list.tag }}>
{% for post in posts %}
   <div class="column{{ post.width }}" >
   </div>
{% endfor %}
</{{ post.list.tag }}>