1

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

表格.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 = ''

模板.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”的东西,所以我可以访问模型的属性。

谢谢你的帮助!

4

1 回答 1

5

You should modify your view like so:

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))

And your template:

{% if selection %}
<tr>
    <td>{{ selection.title }}</td>
    <td>{{ selection.date }}</td>
</tr>
{% endif %}
于 2013-04-16T17:15:34.427 回答