使用listview保存表单中的帖子数据

时间:2015-03-24 23:16:40

标签: django django-class-based-views

我有一份表单列表视图:

class MatchsView(ListView):
    model = Match2x1
    template_name = 'matchs.html'

,模板呈现:

{% for match in object_list %}
    <form action="/apostar/" method="post">{% csrf_token %}
        <p><input type="radio" name="{{match.id}}" value="{{match.team_a}}">{{match.team_a}}</input></p>
        <input type="submit" value="Apostar"></input>
    </form>
{% endfor %}

你可以看到每个表单有两个字段,我需要在DB中保存用户选择的值,使用FormView很容易,但是因为这个时候是一个ListView我有点失去从表单保存在DB中,我知道我必须创建一个处理表单的视图,但实际上我不知道如何创建处理每个表单的发布数据的视图。例如,假设我需要将帖子数据保存在名为FormsMatchs的模型中,我该怎么办?

我正在尝试这个:

class FormView(FormView):
    form_class = FormMatch
    success_url = '/'
    template_name = 'matchs.html'

    def post(self, request, *args, **kwargs):
        hola = Country.objects.create(name=request.POST)

但是保存了这个:

<QueryDict: {u'csrfmiddlewaretoken': [u'tCIQuGlSXKJL0R5eo9R5w09ldeBt7zNW'], u'5': [u'River']}>

1 个答案:

答案 0 :(得分:0)

如果你想拥有一个给定模型的简单列表但是接受一个Form就是使用FormView,并覆盖get_context_data(self, **kwargs)以将查询集传递到上下文中,最好的选择是这样的:

def get_context_data(self, **kwargs):
    context = super(MatchsView, self).get_context_data()
    context['object_list'] = Match2x1.objects.all()
    return context

但是,您也可以将FormMixin与ListView一起使用,请参阅示例here

相关问题