Django动态表单

本文最后更新于:1 年前

def tests(request):

    field_dict={}
    question = models.Questions.objects.all().order_by('id')
    for q in question:
        field_dict['question_%s' %q.id] = fields.CharField(
                    required=False,
                    label = q.title,
                    widget = widgets.Textarea
                )

    MyAnswerForm = type('MyAnswerForm', (Form,), field_dict)

    if request.method == 'GET':
        ini = {}
        for q in question:
            ini['question_%s'%q.id] = q.ans.first().answer
        formset = MyAnswerForm(initial=ini)
        return render(request, 'tests.html', {'formset':formset})

    else:
        ans = MyAnswerForm(request.POST)
        user = models.User.objects.get(id=request.session.get('user_id'))

        if ans.is_valid():
            ans = ans.cleaned_data
            
            for key,v in ans.items():
                k,qid = key.rsplit('_',1)
                try:
                    a=models.Answers.objects.get(question__id=qid, user=user)
                    a.answer=v
                    a.save()
                except models.Answers.DoesNotExist:
                    q = models.objcets.get(id=qid)
                    models.objects.create(user=user, question=q, answer=v)
        formset = MyAnswerForm(request.POST)
        return render(request, 'tests.html', {'formset':formset})
<form action="/tests/" id="answer" method="post">
        {{ formset.management_form }}
        {% csrf_token %}

        {{formset}}
        
        <button type="submit">保存</button>
    </form>

参考资料
https://www.cnblogs.com/ugfly/p/8215384.html


本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!