Django Forms:从ModelChoiceField获取所选项目?

时间:2013-04-16 16:53:07

标签: python django django-forms

我想从ModelChoiceField访问所选项目,类似于:

forms.py

class ManageFeedsForms(forms.Form):
    active_feed = forms.ModelChoiceField(queryset=Feed.objects.all(),
                                         empty_label=None,
                                         widget=forms.Select(attrs={'onchange': 'this.form.submit();'}),
    )

    def __init__(self, *args, **kwargs):
        super(ManageFeedsForms, self).__init__(*args, **kwargs)
        self.fields['active_feed'].label = ''

Template.html

                {% for entry in feed_form.active_feed.selected_item.entry_list %}
                    <tr>
                        <td>{{ entry.title }}</td>
                        <td>{{ entry.date }}</td>
                    </tr>
                {% endfor %}

views.py(非常基本,仅供测试)

def overview(request):
    if request.GET:
        form = ManageFeedsForms(request.GET)
        if form.is_valid():
            pass
        else:
            pass
    else:
        # Empty ManageFeedsForms
        form = ManageFeedsForms()

    return render_to_response('feed_management/home.html',
                              {'header_title': 'Feeds',
                               'feed_form' : form,
                               },
                              context_instance=RequestContext(request))

我正在寻找像'.selected_item'这样的东西,所以我可以访问模型的属性。

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

你应该像这样修改你的观点:

def overview(request):
    selection = None
    if request.GET:
        form = ManageFeedsForms(request.GET)
        if form.is_valid():
            selection = form.cleaned_data['active_feed']
    else:
        # Empty ManageFeedsForms
        form = ManageFeedsForms()

    return render_to_response('feed_management/home.html',
                              {'header_title': 'Feeds',
                               'feed_form' : form,
                               'selection' : selection,
                              },
                             context_instance=RequestContext(request))

你的模板:

{% if selection %}
<tr>
    <td>{{ selection.title }}</td>
    <td>{{ selection.date }}</td>
</tr>
{% endif %}