gpt4 book ai didi

python - 在同一 View 中使用多个表单

转载 作者:太空宇宙 更新时间:2023-11-03 15:27:30 26 4
gpt4 key购买 nike

我正在尝试使用一些示例应用程序来学习 Django 框架。目前,我正在处理反馈/调查应用程序。它使用以下模型:

class Survey(models.Model):
title = models.CharField(_(max_length=255)
slug = models.SlugField(_(max_length=255, unique=True)
description= models.TextField(blank=True)


class Question(models.Model):
survey = models.ForeignKey(Survey, related_name='questions')
question = models.TextField()

class Answer(models.Model):
question = models.ForeignKey(Question, related_name='answers')
answer = models.TextField()

基本上,调查将包含问题,他们的答案将保存在答案中。

现在我不明白的是如何创建一个表单,该表单将在调用 View 时显示调查的所有问题。我试图创建这样的表单

class BaseAnswerForm(Form):
answer = None
def __init__(self, question,*args, **kwdargs):
self.question = question
#self.answer = None
super(BaseAnswerForm, self).__init__(*args, **kwdargs)
answer = self.fields['answer']
answer.label = question.question

def save(self, commit=True):
ans = self.answer
if ans is None:
ans = Answer()
ans.question = self.question
ans.answer = self.cleaned_data['answer']
if commit: ans.save()
return ans

class TextAnswerForm(BaseAnswerForm):
answer = CharField()

def forms_for_survey(survey, request):
if request.POST:
post = request.POST
else:
post = None
return [TextAnswerForm(q,data=post)
for q in survey.questions.all()]

这个的 View 是这样的

def show_questions(request, slug):
survey = get_object_or_404(Survey.objects, slug=slug)
forms = forms_for_survey(survey, request)
context = {
'survey':survey,
'forms':forms,
}
if (request.POST and all(form.is_valid() for form in forms)):
for form in forms:
form.save()
return HttpResponseRedirect(reverse('show_surveys',))
return render_to_response(
'feedback/show_questions.html',
context,
context_instance = RequestContext(request)
)

它的作用是,它根据我的需要生成表单,但所有答案都保存在最后一个答案字段中。请帮助我,使用表单集会更容易吗,你能告诉我如何更容易地实现它吗?谢谢

最佳答案

原因可能是表单字段的名称冲突。

您可以解决该问题,但您是否已经查看了 Formsets Documentation

A formset is a layer of abstraction to working with multiple forms on the same page.

关于python - 在同一 View 中使用多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4723688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com