Django - 在动态HTML表格中

时间:2018-03-11 20:38:31

标签: python django django-models django-forms

我正在尝试创建一个HTML表格,每行有2个字段供用户填写(体育比赛预测)。它从一个表(List)加载数据,并应写入另一个表(Predictions) 现在我有一个循环遍历匹配并基于它创建HTML表。

input.html

{% block body %}
    <form method="post">

        {% csrf_token %}        
        <table class="table">
            <tr>
                <th>Round</th>
                <th>Date</th>
                <th>Time</th>
                <th>Home</th>
                <th class="col-md-1"></th>
                <th class="col-md-1"></th>
                <th class="col-md-1"></th>
                <th>Away</th>
            </tr>
            {% for item in query_results %}
                <tr>
                    <td>{{ item.match_round }}</td>
                    <td>{{ item.match_date }}</td>
                    <td>{{ item.match_time }}</td>
                    <td>{{ item.home_team_name }}</td>
                    <td>{{ form.home_goals_predictions|add_class:"form-control"}}</td>
                    <td class="text-center">:</td>
                    <td>{{ form.away_goals_predictions|add_class:"form-control"}}</td>
                    <td>{{ item.away_team_name }}</td>
                </tr>
            {% endfor %}
        </table>
        <button type="submit" class="btn btn-success">Submit</button>
    </form>        
{% endblock %}

这是有效的,可以随心所欲地显示表格。

但是我无法从中提取数据 - 更准确地说,在提交表单时,最后一行的数据会被分配给所有行。

views.py

query_results = List.objects.all()
form = PredictionsForm()

if request.method == 'POST':
    form = PredictionsForm(request.POST)
    if form.is_valid():
        user_prediction = form.save(commit = False)
        for result in query_results.all():
            for home_goals_predictions, away_goals_predictions in form.cleaned_data.items():
                user_prediction.id = result.id
                user_prediction.match_round = result.match_round
                user_prediction.home_team_name = result.home_team_name
                user_prediction.away_team_name = result.away_team_name
                user_prediction.user_id = request.user.id
                user_prediction.home_goals_predictions = form.cleaned_data['home_goals_predictions']
                user_prediction.away_goals_predictions = form.cleaned_data['away_goals_predictions']
                user_prediction.save()
        return redirect('/matches/')
    else:
        return redirect('/matches/')
else:
    template = loader.get_template('matches/input.html')
    context = {
        'query_results': query_results,
        'form': form
    }
    return HttpResponse(template.render(context, request))

forms.py

class PredictionsForm(forms.ModelForm):
home_goals_predictions = forms.IntegerField(widget=forms.Textarea(attrs={'cols': 1, 'rows': 1, 'maxlength': '2'}))
away_goals_predictions = forms.IntegerField(widget=forms.Textarea(attrs={'cols': 1, 'rows': 1, 'maxlength': '2'}))

class Meta:
    model = Predictions
    fields = ('home_goals_predictions', 'away_goals_predictions')

我真的很感激帮助,因为我遇到了这个问题并且无法使用formset / for循环找出正确的解决方案。

1 个答案:

答案 0 :(得分:0)

我不完全确定您的代码中发生了什么,因为我无法看到query_results的定义,但我非常确定您要查找的是formsets。简而言之,表单提交了一件事/记录。表单集的名称表示一组表单,请参阅the documentation以获取完整示例。另请查看modelformsets,根据您的用例,这可能也会派上用场。

编辑:

是的所以我肯定会去模型组路线。这是一个简短的例子

你的views.py(GET请求)中的

from django.forms import modelformset_factory

ListFormSet = modelformset_factory(List, form=ListForm, extra=0)
list_formset = ListFormSet(queryset=List.objects.all())

然后在POST期间你可以做

ListFormSet = modelformset_factory(List, form=ListForm, extra=0)
list_formset = ListFormSet(request.POST, queryset=List.objects.all())

if list_formset.is_valid():

    for list_form in list_formset:

        list_form.save()

类似于普通单一形式的运作方式。

然后在你的模板中

<form enctype="multipart/form-data" method="post">

    {{ list_formset.management_form }}

    {% for list_form in list_formset %}
        ...
        {{ list_form.instance.match_round }}
        ...
        {{ list_form.home_goals_predictions }} #formfield
        {{ list_form.away_goals_predictions }} #formfield

    {% endfor %}

</form>

如您所见,可以通过.instance

访问查询数据

注意:我从内存中键入了这个内容,因此您可能需要调试一些拼写错误。