将数据从表单传输到Django视图

时间:2019-01-12 17:40:06

标签: django django-forms django-filter

我有一个表格:

    IConfigurationRoot _config;
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        _config = builder.Build();
    }

我需要从旧日期到新日期的数据库中选择数据

class GenereteReport (forms.ModelForm):
    olddate = DateField (widget = forms.DateInput (attrs = {'type': 'date'}))
    newdate = DateField (widget = forms.DateInput (attrs = {'type': 'date'}))

    class Meta:
        model = Transactions
        fields = ['typeOper', 'category']

模型

class ChartData (APIView):
    authentication_classes = []
    permission_classes = []

    def get (self, request, format = None):
        labels = []
        default_items = []
        transacts = Transactions.objects.all ()
        for transact in transacts:
            labels.append (transact.category.name)
            default_items.append (int (transact.suma))
        data = {
            "labels": labels,
            "default": default_items,
        }
        return response (data)

代替日期class Transactions(models.Model): category = models.ForeignKey(Category, blank=True, null=True, default=None, on_delete=models.CASCADE) typeOper = models.ForeignKey(TypeOperation, blank=True, null=True, default=None, on_delete=models.CASCADE) suma = models.DecimalField(max_digits=10000, decimal_places=2, default=0) created = models.DateTimeField(auto_now_add=True, auto_now=False) description = models.TextField(blank=True, null=True, default=None) def __str__(self): return "Category {0}".format(self.category) 来选择日期范围内从底数形式的数据的方法 链接到存储库https://github.com/IvanYukish/PersonalFinanceManager

1 个答案:

答案 0 :(得分:0)

好的,在您的get函数中,您将需要添加代码以正确处理表单并从表单中获取两个经过验证的有效日期。这篇django文档展示了如何做到这一点:django working with forms

一旦您检查表单有效,就可以访问form.cleaned_data,这是一个字典,其中包含表单中所有已清除的字段。 old_date = form.cleaned_data['olddate']将为您提供表单中的第一个日期,第二个也是如此。 有了这些之后,您就可以filter这样Transactions.objects.filter(created__gte=olddate, created_lte=newdate)进行交易了。这就是说,告诉我所有created日期大于或等于olddate且小于或等于newdate的交易。