初学者:以Django CreateView形式动态过滤外键字段

时间:2018-10-05 18:00:43

标签: django

型号:

class Instructional_Cycle(models.Model):
    date_started = models.DateField()
    date_finished = models.DateField()
    standard_tested = models.OneToOneField(Standard, on_delete=models.CASCADE)

class Standard(models.Model):
    subject = models.CharField(max_length=14, choices=subjects)
    grade_level = models.IntegerField(choices=gradeLevels)
    descriptor = models.CharField(max_length=15)
    description = models.TextField()
    essential_status = models.BooleanField(default=False)

查看:

class CycleCreateView(CreateView):
    model = Instructional_Cycle
    template_name = 'cycle_new.html'
    fields = '__all__'
    success_url = reverse_lazy('student_progress:cycles')

模板:

<!-- student_progress/cycle_new.html -->

{% extends 'base.html' %}

{% block content %}
    <h1>Add a new instructional cycle:</h1>

    <form action="{% url 'student_progress:cycle_new' %}" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button name="submit">add cycle</button>
    </form>

{% endblock content %}

此表格存在的问题是,选择Instructional_Cycle.standard_tested的下拉列表实际上具有Standard的1000条记录。用户无法滚动浏览所有这些内容并找到他们想要的一条记录。

我需要某种方法来单击链接,并按主题或grade_level和/或搜索框过滤下拉列表,类似于在admin方面通过在admin.py中创建自定义管理模型来实现的管理方式,如下所示:

class StandardAdmin(admin.ModelAdmin):
    list_display = ('descriptor', 'description', 'essential_status')
    list_filter = ('subject', 'grade_level', 'essential_status')
    search_fields = ('descriptor',)
    inlines = [MilestoneInLine]

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset,         search_term)
        try:
            search_term_as_int = int(search_term)
        except ValueError:
            pass
        else:
            queryset |= self.model.objects.filter(age=search_term_as_int)
        return queryset, use_distinct

请为这个新手“哑巴”。我刚刚完成了面向初学者的Django工作,而关于这一切如何组合的概念模型仍然充满了漏洞。请假设我几乎一无所知。谢谢!

2 个答案:

答案 0 :(得分:0)

您应该考虑使用django-ajax-select之类的东西。 https://github.com/crucialfelix/django-ajax-selects

答案 1 :(得分:0)

在一页上进行大量的被动工作将需要您熟悉Javascript,Ajax等。如果是这种情况,可以采取多种方法来让您用所需的选项刷新表单。

或者,您可以在流程的较早步骤中要求用户提供必要的数据,然后让DOUBLE PRECISION首先让Django为您构建正确的表单。