是否可以实例化一个不使用 {{ formset.as_p }} 调用的表单集?

Is it possible to instantiate a formset which isn't call with {{ formset.as_p }}?

我调用了一个表单集,但没有使用 {{ formset.as_p }},因为我想更改表单的显示。 我知道在使用 {{ formset.as_p }} 时可以实例化一个字段来直接编辑它。

但是这样使用表单集是否可行

<form method="POST" action="">
    {{ formset.management_form }} {% csrf_token %}
    <table>

      <!-- <br>{{ formset.as_p }}<br> -->

      {% for question in questions %}<hr>

    <label for="question">{{ question }} [{{ question.id }}]</label>  
    <input type="hidden" id="id_form-{{ forloop.counter0 }}-question" name="form-{{ forloop.counter0 }}-question" value="{{ question.id }}"/>

  </p>    
    <p>
    <label for="answer">Answer :</label>
    <input type="text" id="id_form-{{ forloop.counter0 }}-answer" name="form-{{ forloop.counter0 }}-answer" placeholder="answer here"/>
    <input type="hidden" id="id_form-{{ forloop.counter0 }}-id" name="form-{{ forloop.counter0 }}-id" value="{{ reply.id }}"/>
    </p>
{% endfor %}

 </table>
    <center><input type="submit" value="Submit" class="btn btn-success" />
    <a href="../../baseVisite/" class="btn btn-success">Retour</a></center>
  </form>

我希望我可以实例化字段答案。

我尝试传递这样的值:

{% for reply in question.reply_set.all %}
    <p>
    <label for="answer">Réponse :</label>
    <input type="text" id="id_form-{{ forloop.parentloop.counter0 }}-answer" name="form-{{ forloop.parentloop.counter0 }}-answer" value="{{ reply.answer }}"/>
    <input type="hidden" id="id_form-{{ forloop.parentloop.counter0 }}-id" name="form-{{ forloop.parentloop.counter0 }}-id" value="{{ reply.id }}"/>
    </p>
  {% endfor %}

但这样做只是初始化值,不允许修改

有没有办法用这个表单集结构做我想做的事?

编辑:

class ReplyForm(forms.ModelForm):

    def __init__(self, page_id, *args,**kwargs):
        super (ReplyForm,self ).__init__(*args,**kwargs)
        self.fields['question'].queryset = Question.objects.filter(page=page_id)

    class Meta:
        model = Reply
        exclude = ('user','creationDate')

如果我没听错,您想自定义使用表单集呈现的表单的视图。当然,您可以这样做,因为 formset 只是一组表单。也渲染 formset manually and do so with the form

<form method="post" action="">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
            {{ form.non_field_errors }}
            <div class="fieldWrapper">
                {{ form.subject.errors }}
                <label for="{{ form.subject.id_for_label }}">Email subject:</label>
                {{ form.subject }}
            </div>
            <div class="fieldWrapper">
                {{ form.message.errors }}
                <label for="{{ form.message.id_for_label }}">Your message:</label>
                {{ form.message }}
            </div>
            # more fields
        {% endfor %}
    </table>
</form>

如果您在一个表单中有多个项目字段(question 在您的情况下),您可以迭代它们并手动呈现:

{% for field in form.question %}
    <div class="fieldWrapper">
        {{ field.errors }}
        <label for="{{ field.id_for_label }}">Some label:</label> {{ field }}
    </div>
{% endfor %}