1

これが私が持っているもの、単純なDjangoフォームです

class survey (forms.Form):
    answer = forms.ChoiceField(
                                 widget = RadioSelect(),
                                 choices = answers_select
                                )

さて、私のHTMLページでは、1つの質問だけでなく、多くの質問がありました。上記のanswerフィールドをすべての質問に使用することは可能ですか?すべての質問に対して、私が示さなければならないのとまったく同じ選択肢です!

3つの質問があるとします。

  1. 私のレストランはどうですか
  2. 食事はいかがですか
  3. サービスはどうですか

answer上記のフィールドの選択肢は次のとおりです1. good, 2. bad 3. worst 。したがって、冗長であるため、3つの質問に対して3つのフォームフィールドを作成したくありません。

4

2 に答える 2

2

一歩下がって、はっきりと考えてください。3ChoiceFieldつの別々の質問の答えを追跡するには3つ必要であり、それを回避する方法はありません。

冗長になるのは、特に20の質問を扱っている場合は特に、フォームフィールド構築の呼び出しを実際に繰り返すことです。この場合、これらのフィールドを静的に作成するのではなく、質問のリストをクラス不変として保存し、フォームの作成中にフォームフィールドを動的に作成できます。

これは、あなたがそれをどのように行うかについての最初のアイデアをあなたに与えるための何かです:

class SurveyForm(forms.Form):
    questions = _create_questions('How is my restaurant?',
                                  'How is the Food?',
                                  'How is the service?')

    def __init__(self, *args, **kwargs):
        # Create the form as usual
        super(SurveyForm, self).__init__(*args, **kwargs)

        # Add custom form fields dynamically
        for question in questions:
             self.fields[question[0]] = forms.ChoiceField(label=question[1],
                                                          widget=forms.RadioSelect(),
                                                          choices=answers_select)
    @classmethod
    def _create_questions(cls, *questions):
        return [(str(index), question) for index, question in enumerate(questions)]
于 2012-10-01T16:19:02.497 に答える
1

フォームセットを探しています。あなたはこのようなことをすることができます:

from django.forms.formsets import formset_factory
SurveyFormSet = formset_factory(survey, extra=3, max_num=3)

コンテキストに追加します。

def get_context_data(self, request, *args, **kwargs):
    data = super(MyView, self).get_context_data(request, *args, **kwargs)
    data['formset'] = SurveyFormSet()
    return data

次に、テンプレートで使用します。

<form method="post" action="">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
        {{ form }}
        {% endfor %}
    </table>
</form>

投稿中に、request.POSTとrequest.FILESをフォームセットコンストラクターに渡す必要があります。

formset = SurveyFormSet(request.POST, request.FILES)

それはすべて、そのリンクされたドキュメントでかなり徹底的に説明されています。

于 2012-10-01T16:12:49.797 に答える