创建动态表单Django

时间:2016-07-08 15:39:43

标签: python django forms

考虑这些Django模型:

class MonitorSession(models.Model):
    agent = models.ForeignKey(Agent, on_delete=models.CASCADE)
    date = models.DateTimeField()
    contact_motive = models.ForeignKey(ContactMotive)
    customer_number = models.CharField(max_length=65)
    protocole_number = models.CharField(max_length=65)
    strong_points = models.TextField(blank=True)
    points_to_improve = models.TextField(blank=True)
    action_plan = models.TextField(blank=True)

    def __unicode__(self):
        return u"%s, %s" % (self.customer_number, self.protocole_number)

class EvaluationCategory(models.Model):
    cel = models.ForeignKey(Cel, on_delete=models.CASCADE)
    category = models.CharField(max_length=65)
    description = models.TextField(blank=True)
    max_points = models.IntegerField()

def __unicode__(self):
    return u"%s: %s" % (self.cel, self.category)


class EvaluationItem(models.Model):
    category = models.ForeignKey(EvaluationCategory, on_delete=models.CASCADE)
    item = models.CharField(max_length=65)

    def __unicode__(self):
        return u"%s: %s" % (self.category, self.item)

class EvaluationScore(models.Model):
    monitor_session = models.ForeignKey(MonitorSession, on_delete=models.CASCADE)
    item = models.ForeignKey(EvaluationItem, )
    score = models.ForeignKey(PossibleScore, on_delete=models.CASCADE)

    def __unicode__(self):
        return u"%s: %s" % (self.item, self.score)

现在我需要使用MonitorSession类中的所有字段创建一个表单。

在这些字段之后,我需要创建动态的其他表单字段,并且将从此查询返回:

fields = EvaluationItem.objects.all().order_by(EvaluationCategory__category)

你可以想象一下,田地的数量是未知的并且是动态的。

Django是否有自动化方法来完成这项工作? Ar我将手动创建表单并为Item字段创建一个循环吗?我一直试图用Formsets完成这项工作,但我不知道formsets如何帮助我。

1 个答案:

答案 0 :(得分:0)

上述建议给了我解决方案的一部分:这将是我的表格的代码:

class MonitorSessionForm(forms.Form):
    agent = forms.ModelChoiceField(queryset=Agent.objects.all())
    date = forms.DateField()
    contact_motive =forms.ModelChoiceField(queryset=ContactMotive.objects.all())
    customer_number = forms.CharField(max_length=65)
    protocole_number = forms.CharField(max_length=65)
    strong_points = forms.CharField(widget=forms.Textarea)
    points_to_improve = forms.CharField(widget=forms.Textarea)
    action_plan = forms.CharField(widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('extra')
        super(MonitorSessionForm, self).__init__(*args, **kwargs)

    for i, item in enumerate(extra):
        self.fields['custum_%s' % i] = forms.CharField(label=item) 

我的模板代码:

{% load bootstrap3 %}
<h2>Fazer Monitoria</h2>
<div class="col-md-6">
    <form method="post" action="">
     {% csrf_token %}
             {% bootstrap_form form %}
         <br><br>
     <input type="submit" name="submit" value="Salvar Monitoria" class="btn btn-primary">
     </form>
     <br><br> 
 </div>

我的观看代码:

@login_required()
def add_monitorsession(request):
     items = EvaluationItem.objects.all()
     if request.method == 'POST':
     form = MonitorSessionForm(request.POST, extra=items)
     if form.is_valid():
        print u'Tudo ok!'
else:
     form = MonitorSessionForm
return render_to_response('add_monitorsession.html', {'form': form})

尝试渲染这个问题给了我一个关键错误:

 KeyError at /addmonitorsession/
 'extra'
 Request Method:    GET
 Request URL:   http://127.0.0.1:8000/addmonitorsession/
 Django Version:    1.9.6
 Exception Type:    KeyError
 Exception Value:   
 'extra'
 Exception Location:         ..../monitoria_altocontato/main/forms/monitor_session.py in __init__, line 19

指出表单的下一行

        extra = kwargs.pop('extra')

任何一个想法?