如何在django表单中为widget提供自定义名称

时间:2013-11-20 11:47:24

标签: django django-forms

我有一个小部件

Comments = forms.CharField(max_length=100,required=True)

现在我想将上面的小部件放在一个循环中,以便它必须生成

Comments_1 = forms.CharField(max_length=100,required=True) 
Comments_2 = forms.CharField(max_length=100,required=True)
Comments_3 = forms.CharField(max_length=100,required=True)  
....
....
....

截至目前,我在django模板中对表单字段进行了硬编码,如下所示 我只想在django表格下面的表格

{% for question in questions %}
            <div class="well">    
                    <h3>{{ question|striptags }} </h3>
                    {% if question.enumComment == "1" %}
                        <br>


                                <textarea name="fill_apraisal_comment{{ question.intQuesID }}" rows="3" cols="40" class="form-control">
                                     {{fill_comments|keyvalue:question.intQuesID}}
                                </textarea> 


                   {% endif %}


            </div>
            {% empty %}
                <li>No Questions.</li>
        {% endfor %}

1 个答案:

答案 0 :(得分:0)

您可以这样做:

from django.utils import six
from django.forms.forms import get_declared_fields
from django.forms.widgets import media_property

class IteratedFieldsMetaclass(type):

    def __new__(cls, name, bases, attrs):

        attrs['base_fields'] = get_declared_fields(bases, attrs)

        i = 0
        while i < 5:
            attrs['base_fields']['Comments_%s' % i] = forms.CharField()
            i = i + 1

        new_class = super(IteratedFieldsMetaclass,
                     cls).__new__(cls, name, bases, attrs)
        if 'media' not in attrs:
            new_class.media = media_property(new_class)
        return new_class

class OrderForm(six.with_metaclass(IteratedFieldsMetaclass, forms.BaseForm)):
    pass

不知道你需要什么,但它有可能:)

编辑(关于评论):

from models import Question

class QuestionIteratedFieldsMetaclass(type):

    def __new__(cls, name, bases, attrs):

        attrs['base_fields'] = get_declared_fields(bases, attrs)

        for question in Question.objects.all():
            attrs['base_fields']['textbox_question%s' % question.id] = forms.CharField(label = question.question_text)

        new_class = super(QuestionIteratedFieldsMetaclass,
                     cls).__new__(cls, name, bases, attrs)
        if 'media' not in attrs:
            new_class.media = media_property(new_class)
        return new_class

喜欢那个?