在Django中从表单中获取None

时间:2018-02-11 18:17:12

标签: python django

在我的一个django中,我有一个在数据库中创建新产品的表单:

views.py

class ProductCreateView(LoginRequiredMixin, CreateView):
    template_name = "products/my-products.html"
    model = Product
    form_class = AddNewProductForm

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user = self.request.user
        obj.save()
        return HttpResponseRedirect("/my-products/")

forms.py

AVAILABLE_YEAR_CHOICES = list(range(1960, 2051))

class AddNewProductForm(forms.ModelForm):

    class Meta:
        model = Product
        fields = ["date", "time", "title", "desrciption"]
        widgets = {'date': forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)}

使用上述内容,一切都很完美。

我想将当前日期和时间添加到日期和时间小部件中,因此我尝试了以下操作:

forms.py

class AddNewProductForm(forms.ModelForm):
    date = forms.DateField(label='date', initial=datetime.date.today(),
                           widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES))
    time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M"))
    class Meta:
        model = Product
        fields = ["title", "desrciption"]

当我使用它时,我收到一个错误,即日期字段为无。

我不确定为什么会发生这种情况。仅使用Meta工作中的字段,但执行自定义操作会给出无。

2 个答案:

答案 0 :(得分:1)

您还需要在第二个示例中指定字段:

class AddNewProductForm(forms.ModelForm):
    date = forms.DateField(label='date', initial=datetime.date.today(),
                           widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES))
    time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M"))
    class Meta:
        model = Product
        fields = ["title", "description", "date", "time"]

答案 1 :(得分:0)

您可以使用get_initial_for_field方法

AVAILABLE_YEAR_CHOICES = list(range(1960, 2051))

class AddNewProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ["date", "time", "title", "desrciption"]
        widgets = {'date': forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)}

    def get_initial_for_field(self, field, field_name):
        if field_name == 'date':
            return datetime.date.today()
        if field_name == 'time':
            return datetime.datetime.now().time()
        return super().get_initial_for_field(field, field_name)

而不是datetime.datetime.now().strftime("%H:%M")做下一个datetime.datetime.now().time()