【问题标题】:exposing data with django form get request使用 django 表单获取请求公开数据
【发布时间】:2017-07-05 04:03:13
【问题描述】:

我正在构建一个小表单,在该表单上显示表格中的一些数据,此外我还有两个dropdown,您可以使用它选择当前数据或年份作为您想要在表。

我的问题是我如何使用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

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

view.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

【问题讨论】:

    标签: python django django-forms django-class-based-views formview


    【解决方案1】:

    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()。它不能在表单上调用它,因为它还没有初始化。将您的方法移动到视图中,您就可以开始了。

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

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

    编码愉快。

    【讨论】:

    • 我想在这个字段上使用select2库,这就是我创建CharFields的原因,我想避免ChoiceField我是对的还是犯了错误,第一次使用select2.
    • 假设您使用的是django-select2just specify the widget in the form(然后按照所有其他安装文档进行操作)。
    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2021-11-01
    • 2018-05-30
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多