无法遍历Django模板中的查询集

时间:2019-03-19 06:11:51

标签: python django

我需要遍历复选框列表,并为每个复选框添加一个链接。但是,我无法这样做。 该模板将完整的表单显示为链接,而不是单个复选框为列表。

下面是我的代码:

这是我的 forms.py

class GetTaskDescription(forms.Form):

    get_tasks = forms.ModelMultipleChoiceField(
        queryset=Task.objects.none(),
        widget=forms.CheckboxSelectMultiple,
        required=True
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(GetTaskDescription, self).__init__(*args, **kwargs)
        self.fields['get_tasks'].queryset = self.user.task_set.all()

    def get_task_description(self):
        tasks = self.cleaned_data['get_tasks']
        return tasks

这是我的 html

{% extends 'todoapp/base.html' %}

{% block title %}Select a Task{% endblock %}

{% block content %}
    <h2>Select tasks to view description</h2>
    <form method="get" action="{% url 'view_task_description' %}" name="view_task_description">
        {% for tasks in view_tasks %}
            <a href="#">{{ tasks }}</a>
        {% endfor %}
        <br/>
        &nbsp;&nbsp;<input type="submit" value="View Description">
        &nbsp;&nbsp;<button onclick="location.href='{%url 'dashboard' %}?name=Go back'" type="button">Go back</button>
    </form>
{% endblock %}

这是我的 views.py

@login_required(login_url='/login/')
def view_task_description(request):
    task_description = GetTaskDescription(data=request.GET, user=request.user)
    if task_description.is_valid():
        obj = GetTaskDescription.get_task_description(task_description)
        print obj
        return render(request, 'todoapp/task_desc.html', context={'description': obj})
    return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)})

1 个答案:

答案 0 :(得分:0)

您要遍历表单实例:

'view_tasks': GetTaskDescription(user=request.user)

{% for tasks in view_tasks %}

要访问字段选择,应在模板中使用view_tasks.fields.get_tasks.choices