gpt4 book ai didi

python - 使用 django 表单获取请求公开数据

转载 作者:行者123 更新时间:2023-12-01 03:18:07 27 4
gpt4 key购买 nike

我正在构建一个小表单,在其中显示表中的一些数据,此外我还有两个下拉列表,您可以使用它们选择当前数据或年份的数据想在表中看到。

我的问题是如何使用django表单获取请求来填充当前月份和年份的dropdown,在我看来,我对如何处理这个有点困惑,请注意,我使用的是 CBV FormView

我尝试过这样的事情表单.py

from django import forms

import datetime


class StatisticsForm(forms.Form):
"""TODO: Simple form with two field, one for year
other for month, so user can list Statistics for
current month and year.
:returns: TODO"""
invoice_month = forms.CharField(label="month", max_length=225)
invoice_year = forms.CharField(label="year", max_length=225)

def get_initial(self):
initial = super(StatisticsForm, self).get_initial()
initial["invoice_month"] = datetime.date.today()
initial["invoice_year"] = datetime.date.today()
return initial

在我看来,我正在显示表格,我需要完成其余的工作。

查看.py

from django.views.generic.edit import FormView

from .models import Rate
from statistics.forms import StatisticsForm
from statistics.services import StatisticsCalculation


class StatisticsView(FormView):
"""
TODO: We need to handle
Total Invoice - no matter how old, basically all of them
Current month Total Invoice
"""
template_name = "statistics/invoice_statistics.html"
form_class = StatisticsForm

def get_context_data(self, **kwargs):
context = super(StatisticsView, self).get_context_data(**kwargs)

def_currency = Rate.EUR

context["can_view"] = self.request.user.is_superuser
context["currency"] = def_currency
context["supplier_statistic"] = StatisticsCalculation.statistic_calculation(default_currency)
return context

最佳答案

FormView创建实际的表单对象,它从 get_form_kwargs() 获取要传递给表单的参数:

def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs

注意它是如何调用get_initial()的其本身( View )而不是形式。它无法在表单上调用它,因为它尚未初始化。将您的方法移至 View 中,就可以开始了。

作为旁注,使用 django.utils.timezone.now()与 stdlib datetime.date.today() 相反因为它尊重您的 django 时区设置,否则您可能偶尔会看到一些相差一的怪癖。

编辑:您还应该更新表单以使用 ChoiceField ,并使用 timezone.now().month 设置默认值和timezone.now().year .

祝你编码愉快。

关于python - 使用 django 表单获取请求公开数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42267252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com