如何在单个模板中为每个条目分隔输入表单

时间:2018-12-21 21:44:31

标签: html django forms list view

我有一个显示在网页上的条目列表。每个条目具有相同的输入形式。但是,当数据输入到输入表单中时,就会出现我的问题,它出现在每个输入表单中。我该如何更改。

每种输入形式都被视为分布在许多条目上的单个克隆实体。

views.py

  

def topic(请求,topic_id,类型):#

topic = Topic.objects.get(id = topic_id, type = 't_topic')


entries = topic.entry_set.order_by('-date_added')

images = Image.objects.filter(imgtopic__in = entries)


ArticleFormSet = formset_factory(CheckAnswer, extra = 2)


if request.method == 'POST':

    formset = ArticleFormSet(request.POST) 

    if form.is_valid():

        return HttpResponseRedirect(reverse('learning_logs:index'))
else:

    formset = ArticleFormSet() 




context = {'topic': topic, 'entries': entries, 'images': images, 'formset': formset}
return render(request, 'learning_logs/topic.html', context)

topic.html模板

  

{%load staticfiles%}   {%块内容%}

{用于输入项的%(n)%}

<div class = 'secondary-container'> 

    <li>


    <div class = 'date'>
        <p >{{ entry.date_added|date:'M d, Y H:i'}}</p>
    </div>




        {%include 'learning_logs/view_files.html'%}


    <div class = 'video-container'>
        {%include 'learning_logs/video.html' %}
    </div>

    <div class = 'entry-text'>
        <p>{{ entry.text|linebreaks }}</p>
        <p>$ {{entry.price_set.get.ptext}}</p>
    </div>

    </li>

    <li> 


        <p> Enter Answer: </p>

        <form action = "{%url 'learning_logs:topic' topic.id topic.type%}" method = 'post'>

            {{formset.management_form}}
            <table> 
                {% for form in formset%}
                        {{form.as_p}}
                        {% csrf_token %}
                        <button name = "submit">Submit answer</button>


                {% endfor %}
            </table>



        </form>





</div>

forms.py

  

CheckAnswer(forms.Form)类:

your_answer = forms.CharField(label = "Enter Your Key", max_length = 100)

def clean(self):

    cleaned_data=super(CheckAnswer, self).clean() 
    your_answer = cleaned_data.get("your_answer")

    try: 

        p = Keys.objects.get(key = your_answer)
    except Keys.DoesNotExist: 

        raise forms.ValidationError("Incorrect code.")

我的新问题是我无法将表单分成不同的列表。由于extra = 2,因此我在同一条目列表上获得了2个表单实例。

我试图在topic.html模板中使用{%for form in formset%}命令为每个条目提供一个表单,但是当我单击时,出现了['ManagementForm数据丢失或被篡改']提交。

Image of the problem

0 个答案:

没有答案