动态Django表单字段基于ForeignKey

时间:2013-09-08 02:43:18

标签: python django forms

我正在尝试为给定问题组中的每个问题创建一个表单字段。我对python / django很新,所以这可能是一个糟糕的方法,欢迎高层建议。这就是我所拥有的:

models.py:

class QuestionGroup(models.Model):
    name = models.CharField(max_length = 50)
    creator = models.ForeignKey(User)
    modified = models.DateTimeField()

class Question(models.Model):
    question_content = models.CharField(max_length = 100)
    question_group = models.ForeignKey(QuestionGroup)

views.py:

def give_feedback(request, group_id):
    question_list = Question.objects.filter(question_group = group_id)
    form = ResponseForm(question_list)

forms.py:

class ResponseForm(forms.Form):
    def __init__(self, *args, **kwargs):
        for q in args:
            q.question_content = forms.CharField(max_length = 100)

我得到''ResponseForm'对象没有属性'_errors'“。想法?

1 个答案:

答案 0 :(得分:2)

不确定这是否是问题所在,但您应该在覆盖的__init __中调用父Form初始化方法:

def __init__(self, *args, **kwargs):
    super(ResponseForm, self).__init__(*args, **kwargs)

    for q in args:
        q.question_content = forms.CharField(max_length = 100)