带有单个提交按钮的多个表单

时间:2013-07-29 14:52:49

标签: django django-forms multiple-forms

我目前正在使用django项目。我必须根据表单上的用户输入(模板)过滤数据库中的数据存储,如下所示。

enter image description here

在表单上,​​用户输入值或将其留空。所以我要做的是首先找到(有效的)用户输入,然后触发相应的查询以在表单中显示数据作为用户输入。因此,最终结果应显示在模板的表格中。

由于我是django的新手,我应该如何传递数据并触发查询来表示多个字段的数据。作为与这些类型问题相关的帮助或链接是预期的。 (我只能用一个表单从数据库中过滤掉,没有解决这个问题的概念。)

我的临时项目模型如下。

class exReporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
    gender = models.CharField(max_length=1)
    age = models.IntegerField()
    label = models.IntegerField()

1 个答案:

答案 0 :(得分:1)

您可以采取多种方法,但这里有一种解决方案,您可以根据表单的发布数据将相应的过滤器链接在一起:

*注意:要符合Python的命名约定,请将 exReporter 类重命名为 ExReporter

# views.py
def process_ex_reporter_form(request):
    if request.method == "POST":
        # ExReporterForm implementation details not included.
        ex_reporter_form = ExReporterForm(request.POST)

        if ex_reporter_form.is_valid():
            # If form field has no data, cleaned data should be None.
            gender = ex_reporter_form.cleaned_data['gender']
            age_start = ex_reporter_form.cleaned_data['age_start']
            age_end = ex_reporter_form.cleaned_data['age_end']
            aggregation_group = ex_reporter_form.cleaned_data['aggregation_group']
            aggregation_id = ex_reporter_form.cleaned_data['aggregation_id']

            ex_reporters = ExReporter.objects.get_ex_reporters(gender, age_start,
                               age_end, aggregation_group, aggregation_id)

        else:
            # Pass back form for correction.
            pass

    else:
        # Pass new form to user.
        pass

# models.py
class ExReporterManager(models.Manager):
    def get_ex_reporters(self, gender, age_start, age_end, aggregation_group,
                         aggregation_id):

        ex_reporters = super(ExReporterManager, self).get_query_set().all()

        # Even though the filters are being applied in separate statements,
        # database will only be hit once.
        if ex_reporters:
            if gender:
                ex_reporters = ex_reporters.filter(gender=gender)

            if age_start:
                ex_reporters = ex_reporters.filter(age__gt=age_start)

            if age_end:
                ex_reporters = ex_reporters.filter(age__lt=age_end)

            # Apply further filter logic for aggregation types supported.

        return ex_reporters