Django动态表单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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})

1
2
3
4
5
6
7
8
<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


Django动态表单
https://blog.yrpang.com/posts/4202/
作者
yrPang
发布于
2019年7月28日
许可协议